2016-11-25 90 views
2

我想为组件创建一个基类,以便能够在组件的生命周期中执行一些常见操作。我也需要基类来访问一些服务。我如何注入它?当然,我可以使用单身而不是服务,但即使不打字,我也不会很有倾向性,因为单身人士在那里是反模式。 映入眼帘, 丹尼尔将Angular2服务注入组件基类

编辑:

这是目前工作的,但我宁愿有望使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 }; 

回答

1

Angular2仅支持构造器注入。如果你有一个超类和子类,并要注入到超类,你必须构造函数参数添加到子类,并将其转发到子类

export class RemoteController implements OnInit { 

    constructor(public connection: SocketIOClient.Socket) { 
     this.connection = RemoteService.connect('ws://localhost:8500'); 
    } 
@Component(...) 
export class SomeComponent extends RemoteController { 
    constructor(connection: SocketIOClient.Socket) { 
     super(connection 
+0

这是绝对不是我想听到的。我还通过ReflectiveInjector了解了一些关于程序化注入的内容,但是我没有把它做好。在接受这个令人满意的答案之前,我会再调查一下(谢谢Günter) – Daniel

+0

如果您使用'ReflectveInjector',您仍然需要注射应用注射器。我用示例代码发布了一些答案。我甚至不想尝试解决,我认为这不会奏效。 –

+1

*在基类的构造函数参数中不添加“public”,“private”或“protected”非常重要,否则会发生冲突。这个例子没有包括它们,但我仍然包括它们,直到我明白了。 – vt5491