我擴展了XHRBackend
類,我想注入我的全局服務,提供自舉。我試圖通過構造器注入它Angular2:無法解析全球服務
export class AppXHRBackend extends XHRBackend {
constructor(
browserXHR: BrowserXhr,
baseResponseOptions: ResponseOptions,
@Inject(AppState) private app: AppState) {...}
...
}
但我得到undefined
。然後我試圖通過注射器手動解決它:
export class AppXHRBackend extends XHRBackend {
constructor(browserXHR: BrowserXhr, baseResponseOptions: ResponseOptions) {
let injector = ReflectiveInjector.resolveAndCreate([AppState]);
let app = injector.get(AppState);
...
}
我的AppState
實例,但是,這是新的實例,我認爲這是正確的,它應該是這樣的,但我想我的單獨服務。
這裏是我bootsrap應用:
bootstrap(App, [
...
AppState,
provide(ExceptionHandler, {useClass: AppExceptionHandler}),
provide(XHRBackend, {useClass: AppXHRBackend})
])
這裏是我的服務:
import { Injectable, EventEmitter } from '@angular/core';
@Injectable()
export class AppState {
...
}
順便說一句,我的服務AppState
很好的AppExceptionHandler
類通過它的構造injectes:
export class AppExceptionHandler extends ExceptionHandler {
constructor(@Inject(AppState) private app: AppState) {...}
...
}
而且我沒有看到非常大的差異這兩個擴展,所以我不明白爲什麼它不起作用AppXHRBackend
一般來說,我只是希望我的全球服務,以處理全球401,403,404狀態碼。也許我會爲了這個目的而錯誤的做法?
UPD 經由UseFactory
TY @yurzui通過提供解決:
{
provide: XHRBackend,
useFactory: (browserXHR: BrowserXhr,
baseResponseOptions: ResponseOptions,
xsrfStrategy: XSRFStrategy,
appState: AppState) => new AppXHRBackend(browserXHR, baseResponseOptions, xsrfStrategy, appState)
,
deps: [BrowserXhr, ResponseOptions, XSRFStrategy, AppState]
}
是否'AppState'有參數的構造函數? –