2016-11-25 91 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