简体   繁体   中英

how to implement socket.io in angular

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)
          }
        })
      })
    }
  }
})

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));
    });
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM