Reputation: 655
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)
}
})
})
}
}
})
Upvotes: 0
Views: 162
Reputation: 137
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));
});
}
Upvotes: 1