Angular2 View Not Changing After Data Is Updated

前端 未结 6 1411
长情又很酷
长情又很酷 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条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 16:30

    Just move your socket.io initialization to Service constructor and it will work.
    Take a look at this example:

    import {Injectable} from 'angular2/core';  
    @Injectable()
    export class SocketService {
        socket:SocketIOClient.Socket;
    
        constructor(){
            this.socket = io.connect("localhost:8000");
        }
        public getSocket():SocketIOClient.Socket{
            return this.socket;
        }
    }
    

    Now whenever you inject this service to a component and use a socket, your view will automatically update. But if you leave it in a global scope like you did, you will have to interact with something in order to force the view to update.
    Here is an example component that uses this service:

    export class PostsComponent {
        socket: SocketIOClient.Socket;
        posts: Array = [];
    
        constructor(private _socketService:SocketService){
            this.socket.on('new-post', data => {
                this.posts.push(new Post(data.id, data.text));
            });  
    }  
    

提交回复
热议问题