2016-10-31 39 views
0

使用Angular2,在组件之间共享全局(socket.io)对象的最佳方式是什么?特别是从RootComponent到一个ChildComponent。全局socket.io - Angular2

在我app.component.ts,我存储这样

export class AppComponent { 
    socket: any; 

    constructor() { 

    this.socket = io('localhost:3000'); 
    } 
} 

然后套接字试图通过应用程序来引用它:ApplicationRef这个

export class FileListComponent { 
    app: any; 
    constructor(app:ApplicationRef) { 
     this.app = app; 
     this.app.socket; // <== 
    } 
} 

但this.app不直接引用该实例,并找不到它。

是否有最佳做法?

感谢

+0

的[分享在角2的多个组件之间的WebSocket数据的最佳方法是什么?(HTTP可能重复:// stackoverflow.com/questions/37025837/the-best-way-to-share-websocket-data-between-multiple-components-in-angular-2) – echonax

回答

1

,最好的办法是初始化套接字IO:在共享服务(@Injectable)(“本地主机3000”),并且无论你想比注入该服务。这是共享组件

之间的任何东西的最佳方式这很容易帮助您创建一个:https://angular.io/docs/ts/latest/tutorial/toh-pt4.html