簡體   English   中英

如何將服務注入Angular2中的類實例(不是服務)?

[英]How to inject services into instances of classes (that not services) in Angular2?

我有下一個解決方案,但是angular2的最佳做法是什么?

...

class MultitonObject {
    _http: Http;

    constructor (appInjector: Injector) {
        this._http = appInjector.get(Http);
    }
}

var app = bootstrap(AppComponent, [HTTP_PROVIDERS, ...]);

app.then(componentRef => {
  var new_instance = new MultitonObject(componentRef.injector);
});

Angulars依賴注入只能注入到它自己創建的類中。 如果您使用new MyClass()自己創建實例,Angular將無能為力。

您問題中的代碼適用於此用例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM