Global socket.io - Angular2

时间:2016-10-31 21:17:26

标签: angular

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

在我的app.component.ts中,我存储了一个像这样的套接字

export class AppComponent {
  socket: any;

  constructor() {

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

然后尝试通过app引用它:ApplicationRef this

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

但是this.app并没有直接引用该实例,也无法找到它。

有最好的做法吗?

由于

1 个答案:

答案 0 :(得分:1)

最好的方法是在共享服务(@Injectable)中初始化套接字io('localhost:3000'),而不是在任何地方注入该服务。这是在组件之间共享任何内容的最佳方式

这可以轻松帮助您创建一个:https://angular.io/docs/ts/latest/tutorial/toh-pt4.html