Angular2 View Not Changing After Data Is Updated

前端 未结 6 1428
长情又很酷
长情又很酷 2020-12-09 15:42

I am trying to update my view after a websocket event returns updated data.

I injected a service into my app and call getData() method on the service. This method em

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 16:36

    UPDATE

    The plunker I linked provided a base example but it frustrates me that I couldn't show an entire "working example". So I created a github repo that you can pull down to see a full working example of the pieces I talked about below.


    So in your actual question there were two problems. You had a typo in the original code in the "MyService.ts" file

    self.someList = data;//should be this.someList, self is the browser window object
    

    Another issue is Angular2 doesn't recognize change detection the way you're expecting it to. If it had been set to 'this', I still don't think it would have updated your component view.

    In your answer, it does work but you're kind of going around the issue the wrong way. What you should implement is an Observable in your service.

    When you combine these two features together you can implement sails in a fairly straight forward way. I have created an example plunker but keep in mind that it doesn't actually connect to a sails server because plunker requires https and I'm not going to go buy a ssl cert for my local machine. The code does reflect how you should implement communication with sails in Angular2.

    The basic idea can be found in the src/io.service.ts file

    constructor() {
      this._ioMessage$ = >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
        });
      }
    }
    

提交回复
热议问题