【问题标题】:Injecting Angular2 Service into components base class将Angular2服务注入组件基类
【发布时间】: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


    【解决方案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
    

    【讨论】:

    • 这绝对不是我想听到的。我还通过 ReflectiveInjector 阅读了一些关于程序化注入的信息,但我没有让它正常工作。在接受这个不满意的答案之前,我会进行更多调查(无论如何感谢 Günter)
    • 如果使用ReflectveInjector,仍然需要注入应用程序注入器。我用示例代码发布了一些答案。我什至不会尝试解决问题,我认为这不会很好。
    • 重要的是不要在基类的构造函数参数上添加“public”、“private”或“protected”,否则会发生冲突。该示例正确地不包含它们,但无论如何我都包含它们,直到我弄明白为止。
    猜你喜欢
    • 2017-08-11
    • 1970-01-01
    • 2016-05-09
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    相关资源
    最近更新 更多