1

Is there a way to instantiate sails.io inside the zone of a service provider in Angular2 so that websocket events trigger change detection?

A sub-question: how to RXJS to subscribe to sails.io data streams. I'm using Angular2 RC4, and the latest version of SailsJS.

Related question: Angular2 View Not Changing After Data Is Updated

Community
  • 1
  • 1
ktamlyn
  • 4,519
  • 2
  • 30
  • 41

1 Answers1

2

UPDATE

It annoyed me that I couldn't give a full example of how to use Sails with Angular 2 with just plunker, so I created a github repo, that provides the full picture on how this can work.


I can see how the related question you linked, would lead you down the zone path. However, you can plug all of this together without having to manually tinker with zones. Here is an example of how you could implement sails.io with Angular2 in a plunker. This leverages using RxJS to create a type of observable. You also have to implement a different version of Angular2 change detection(all of this is implemented in the plunker).

I go into a little more detail in my answer to your linked question.

As for your sub question I'm not sure if there is a way to integrate the stream, I believe one of the intentions of RxJS was to reduce the use of callbacks, which sails.io appears to still do.

Excerpt of implementing sails.io in a service from the plunker.

constructor() {
  this._ioMessage$ = <Subject<{}>>new Subject();
  //self is the window object in the browser, the 'io' object is actually on global scope
  self.io.sails.connect('https://localhost:1337');//This fails as no sails server is listening and plunker requires https
  this.listenForIOSubmission();
}

get ioMessage$(){
  return this._ioMessage$.asObservable();
}

private listenForIOSubmission():void{
  if(self.io.socket){//since the connect method failed in the constructor the socket object doesn't exist
    //if there is a need to call emit or any other steps to prep Sails on node.js, do it here.
    self.io.socket.on('success', (data) => {//guessing 'success' would be the eventIdentity
      //note - you data object coming back from node.js, won't look like what I am using in this example, you should adjust your code to reflect that.
      this._ioMessage$.next(data);//now IO is setup to submit data to the subscribbables of the observer
    });
  }
}
Community
  • 1
  • 1
Dan Simon
  • 824
  • 6
  • 7
  • I believe the syntax `>` is depreciated. The new syntax would be `this._ioMessage$ = new Subject() as Subject<{}>;` – ktamlyn Jul 20 '16 at 16:28