1
對於不爲此代碼創建運行程序,我提前表示歉意,因此需要運行一些第三方控件。如何在運行時確定可注入角度服務?
我的問題是關於在運行時根據一些條件選擇服務,依賴注入。
讓我們討論這個例子中只有一個服務。
import { Injectable } from '@angular/core';
import { Http, Response} from '@angular/http';
@Injectable()
export class Service1 {
constructor (
private http: Http) {
}
}
在我的組件中,如果我有一個固定的,一切都很好。
import {Component, ViewChild, OnChanges, Input, ReflectiveInjector, SimpleChange} from '@angular/core';
import {Observable} from 'rxjs/Rx';
import { Service1 } from './my.service.1';
@Component({
providers: [
Service1
],
moduleId: module.id,
selector: 'my-component',
templateUrl: './my-component.component.html'
})
export class MyComponent {
constructor(private service : Service1
) {
}
在上述情況下一切正常,沒有運行時錯誤。
現在,如果我更改爲動態版本,則會收到錯誤 異常:http://localhost:3000/app/app.component.html:5:8中的錯誤由以下原因引起:沒有提供程序用於Http! (服務1 - > HTTP)
的代碼導致錯誤的版本是:
我添加MyComponent的一個成員變量:私人服務:任何= '';
和構造函數現在看起來像
constructor() {
// this does not work with the http module
let injector = ReflectiveInjector.resolveAndCreate([Service1]);
this.service = injector.get(Service1);
}
有人看見是什麼原因造成了上述的錯誤?
沒有變化後,我加了你的建議。 – reza
對不起,我只是找你,它很難,因爲Http有它自己的依賴關係,這些依賴關係有它們的依賴關係,所以你必須提供所有這些依賴關係給'ReflectiveInjector'以獲得你的'Service1'。看看這裏https://github.com/mgechev/injection-js –