2016-05-08 243 views
1

使用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 ...所以我应该忘记我的服务声明中的某些内容,但是什么?

+0

你的代码看起来不错,你可能有多个'ConfigService'类吗?是'../ services/ConfigService'和bootstrap中的一样吗? – Abdulrahman

+0

Arggghh,你是对的!麻烦大写/小写!多谢 !!! – user3779825

+0

不客气,很高兴提供帮助。 – Abdulrahman

回答

0

提供者只能在引导应用程序或组件级别时定义。

因此,您可以在此级别定义ConfigService。

详情请参阅此问题:

关于AuthService,我不知道你是怎么定义它的供应商,但如果你利用useFactory对于这一点,你需要明确定义它的依赖关系(包括ConfigService)。这里是一个样本:

provide(AuthService, { 
    useFactory: (config) => { 
    return new... 
    }, 
    depend: [ ConfigService ] 
}); 
相关问题