【发布时间】:2017-04-09 14:22:39
【问题描述】:
我想为组件创建一个基类,以便能够在组件的生命周期中做一些常见的事情。我还需要基类来访问某些服务。我该如何注射?当然,我可以使用单例而不是服务,但我想即使不是打字稿也不会很刻板,因为单例在那里是一种反模式。 问候, 丹尼尔
编辑:
这是目前正在工作的,但我更希望将 ConnectionService @Injectable() 注入到 RemoteController 的构造函数中,就像 Angular2 文档说的那样,最好不需要将其添加到子组件提供者列表中。
子组件:
@Component(...)
export class SomeComponent extends RemoteController {
sendRequest() {
this.request('something');
}
}
基类:
export class RemoteController implements OnInit {
public connection: SocketIOClient.Socket;
constructor() {
this.connection = RemoteService.connect('ws://localhost:8500');
}
request(name: string) {
this.connection.emit('request', name);
}
ngOnInit() {
...
}
}
单例解决方案:
class ConnectionService {
private sockets: { [key: string]: SocketIOClient.Socket };
constructor() {
debugger;
this.sockets = {};
}
connect(url: string) {
return (url in this.sockets) ? this.sockets[url] : io.connect(url);
}
}
let RemoteService = new ConnectionService();
export { RemoteService };
【问题讨论】:
标签: angular service code-injection