0

i have socket.io as service which works in angularJS but i trying to reimplement it as service in angular. any idea on how to:

here is the implementation in angularJS:

angular.module('App')
.factory('socket', function ($rootScope) {
  var socket = io.connect()
  return {
    on: function (eventName, callback) {
      socket.on(eventName, function () {
        var args = arguments
        $rootScope.$apply(function () {
          callback.apply(socket, args)
        })
      })
    },

    emit: function (eventName, data, callback) {
      socket.emit(eventName, data, function () {
        var args = arguments
        $rootScope.$apply(function () {
          if (callback) {
            callback.apply(socket, args)
          }
        })
      })
    }
  }
})
1

1 Answer 1

1

To create a socket.service.ts file (make sure to add it in providers section of app.module.ts and import the service in the component which uses it):

import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable, Subject } from 'rxjs';
import { Observer } from 'rxjs';

const SERVER_URL = 'http://localhost:3000';

@Injectable()
export class SocketService {
  private socket;

  public initializeSocket() {
    this.socket = io(SERVER_URL);
  }
}

To implement your listeners(observables) and emiters:

  public emitSomething(data) {
    this.socket.emit('emittingSomething', data);
  }

  public onGotSomething(): Observable<data> {
    return new Observable<data>((observer) => {
      this.socket.on('receivedSomething', (myData: data) => observer.next(myData));
    });
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.