将Angular2 Service注入组件基类

时间:2016-11-25 08:33:51

标签: angular service code-injection

我想为组件创建一个基类,以便能够在组件的生命周期中执行一些常见操作。我还需要基类来访问某些服务。我怎么注射它?当然,我可以使用单身而不是服务,但是我认为,即使不是俗名,也不会有很大的角度,因为单身人士在那里是反模式。 映入眼帘, 丹尼尔

修改

这是目前正在运行的,但我更希望将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() {
        ...
    }
}

Singleton解决方案:

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 个答案:

答案 0 :(得分: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
相关问题