使用Angular2 RC1將自定義服務注入到自定義服務
假設我有兩個自定義服務:例如ConfigService和AuthService。
並且還假定AuthService需要ConfigService中的數據。
ConfigService的就是這樣
import { Injectable } from '@angular/core';
@Injectable()
export class ConfigService {
public baseURL: string;
constructor() {
this.baseURL = 'http://localhost:8080';
}
}
我的ConfigService必須是單身,所以我在我的引導供應商陣列聲明它:
bootstrap(MyWayAppComponent, [
HTTP_PROVIDERS,
...
ConfigService
]);
沒有問題,當我嘗試注入我的任何組件中的ConfigService,我總是獲取相同的實例。
但現在我想在我的AuthService注入這個ConfigService的(AuthService不是獨立的,並在我的身份驗證組件提供)
我注入的ConfigService在我AuthService如下:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { ConfigService } from '../services/ConfigService';
@Injectable()
export class AuthService {
constructor(private http: Http, private configService: ConfigService) {
}
}
和響應是:
EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in :0:0
ORIGINAL EXCEPTION: No provider for ConfigService!
ORIGINAL STACKTRACE:
Error: DI Exception
at NoProviderError.BaseException [as constructor] (http://localhost:4200/vendor/@angular/core/src/facade/exceptions.js:17:23)
at NoProviderError.AbstractProviderError [as constructor] (http://localhost:4200/vendor/@angular/core/src/di/reflective_exceptions.js:39:16)
at new NoProviderError (http://localhost:4200/vendor/@angular/core/src/di/reflective_exceptions.js:75:16)
at ReflectiveInjector_._throwOrNull (http://localhost:4200/vendor/@angular/core/src/di/reflective_injector.js:776:19)
at ReflectiveInjector_._getByKeyDefault (http://localhost:4200/vendor/@angular/core/src/di/reflective_injector.js:804:25)
at ReflectiveInjector_._getByKey (http://localhost:4200/vendor/@angular/core/src/di/reflective_injector.js:767:25)
at ReflectiveInjector_.get (http://localhost:4200/vendor/@angular/core/src/di/reflective_injector.js:576:21)
at ElementInjector.get (http://localhost:4200/vendor/@angular/core/src/linker/element_injector.js:23:48)
at ElementInjector.get (http://localhost:4200/vendor/@angular/core/src/linker/element_injector.js:23:48)
at ReflectiveInjector_._getByKeyDefault (http://localhost:4200/vendor/@angular/core/src/di/reflective_injector.js:801:24)
ERROR CONTEXT:
[object Object]
我已經仔細閱讀優秀帕斯卡爾普雷希特文章,但我不看到我錯了... http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html
注意:如果我的AuthService嘗試注入「常規」服務(如http)我沒有pb ...所以我應該忘記我的服務聲明中的某些內容,但是什麼?
你的代碼看起來不錯,你可能有多個'ConfigService'類嗎?是'../ services/ConfigService'和bootstrap中的一樣嗎? – Abdulrahman
Arggghh,你是對的!麻煩大寫/小寫!多謝 !!! – user3779825
不客氣,很高興提供幫助。 – Abdulrahman