2016-11-03 31 views
2

我實現了http攔截器服務,但它工作正常,但我的問題是我無法弄清楚如何在提供聲明中注入我自己的服務。Angular 2:無法在提供程序中使用useFactory注入服務

我在控制檯中得到運行時錯誤:No provider for MyService

HttpService的攔截器類:

// all the imports... 

@Injectable() 
export class HttpService extends Http { 
    constructor(backend: ConnectionBackend, 
       defaultOptions: RequestOptions, 
       private router: Router, 
       private injector: ReflectiveInjector, 
       private myService: MyService){ 
    super(backend, defaultOptions); 
    } 

    // methods... 

在我app.module.ts,我有供應商的數組:

[ 
{ 
    provide: 'MyService', 
    useClass: MyService 
}, 
{ 
    provide: 'Http', 
    useFactory: (xhrBackend: XHRBackend, 
       requestOptions: RequestOptions, 
       router: Router, 
       injector: ReflectiveInjector, 
       myService: MyService) => 
     new HttpService(xhrBackend, requestOptions, router, injector, myService), 
    deps: [XHRBackend, RequestOptions, Router, Injector, MyService] 
}] 

我檢查了幾個SO問題/答案,但couldn」 t找到一個類似的例子..

謝謝!

回答

3

deps只說明工廠需要什麼樣的依賴關係(以便它們可以正確注入)。但它實際上並不提供依賴性。你仍然需要將其添加到providers陣列

providers: [ 
    MyService, 
    { 
    provide: 'Http', 
    ... 
    } 
] 
+0

我已經更新了我的問題,所以你可以調整,我使用{提供:「爲MyService」,useClass:爲MyService},在我的供應商陣列,但只是爲MyService只有(如你所建議的)工作! –

相關問題