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