【问题标题】:Using SailsJS sails.io with Angular 2在 Angular 2 中使用 SailsJSsails.io
【发布时间】:2016-11-19 18:23:47
【问题描述】:

有没有办法在 Angular2 的服务提供者区域内实例化 sails.io,以便 websocket 事件触发更改检测?

一个子问题:RXJS 如何订阅sails.io 数据流。 我正在使用 Angular2 RC4 和 SailsJS 的最新版本。

相关问题:Angular2 View Not Changing After Data Is Updated

【问题讨论】:

    标签: javascript angular websocket socket.io sails.js


    【解决方案1】:

    更新

    我无法给出一个完整的例子来说明如何使用带有 Angular 2 的 Sails 和 plunker,这让我很恼火,所以我创建了一个 github repo,它提供了它如何工作的完整图片。


    我可以看到您链接的相关问题将如何引导您进入区域路径。但是,您可以将所有这些连接在一起,而无需手动修改区域。 Here 是一个示例,说明如何在 plunker 中使用 Angular2 实现sails.io。这利用了使用 RxJS 创建observable 的类型。您还必须实现不同版本的 Angular2 change detection(所有这些都在 plunker 中实现)。

    我在回复您的linked question 时会更详细一点。

    至于您的子问题,我不确定是否有办法集成流,我相信 RxJS 的目的之一是减少回调的使用,sails.io 似乎仍然这样做。

    在 plunker 的服务中实现sails.io 的摘录。

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

    【讨论】:

    • 我相信语法 &lt;Subject&lt;{}&gt;&gt; 已被贬低。新语法为this._ioMessage$ = new Subject() as Subject&lt;{}&gt;;
    猜你喜欢
    • 1970-01-01
    • 2016-06-26
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    相关资源
    最近更新 更多