2016-10-31 54 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