With Angular2, what is the best way to share a global (socket.io) object between components? Especially from the RootComponent to a ChildComponent.
In my app.component.ts, I store a socket like this
export class AppComponent {
socket: any;
constructor() {
this.socket = io('localhost:3000');
}
}
And then try to reference it through app:ApplicationRef this
export class FileListComponent {
app: any;
constructor(app:ApplicationRef) {
this.app = app;
this.app.socket; // <==
}
}
But this.app doesn't hold a direct reference to the instance, and couldn't find it either.
Is there a best practise for that?
Thanks
The best way would be to initialize the socket io('localhost:3000') in a shared service (@Injectable), and than Inject that service wherever you want. This is the best way of sharing anything between components
This could easily help you create one: https://angular.io/docs/ts/latest/tutorial/toh-pt4.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.