以下是该方案。我注入了两项服务。我想确保一些数据,例如将基本URL传递给第一个服务,以便所有后续服务都可以访问它。
这是我的根组件
export class AppCmp {
constructor (private httpService:HttpService, private SomeService:someService){}
}
这是第一个服务,我们假设它是一个自定义的httpSerive
@Injectable()
export class HttpService{
BASE_URL:string;
constructor(private http:Http){
}
getAll(){ return this.http.get(this.BASE_URL) }
}
这是第二个服务,它将依赖于第一个服务来执行http.get请求。
@Injectable()
export class SomeService{
constructor(private httpSerivce:HttpSerivce){
this.httpService.getAll()...
}
}
我不想将基本URL(或数据)硬编码到服务中,我不想涉及localStorages,所以我有两个选择:在main.ts(bootstrap文件)或root组件中,假设他们是分开的。
重要的是数据首先可用,并且可以通过第一个注入的服务传递或抓取。
希望我能说明一下这个主题,谢谢!
答案 0 :(得分:1)
您可以提供各种价值。
使用字符串键(或OpaqueToken
)
{provide: 'BASE_URL', useValue: someUrl}
并像
一样注入它constructor(@Inject('BASE_URL') private baseURL:string)
答案 1 :(得分:1)
RC4 在main.ts
let injector = ReflectiveInjector.resolveAndCreate(HTTP_PROVIDERS);
let http = injector.get(Http);
let authService = new AuthService(new LocalStorage(),http);
authService.BASE_URL='you url goes here'
bootstrap(AppComponent, [
APP_ROUTER_PROVIDERS,
[provide(AuthService, {useValue: authService})],
]).catch(err => console.error(err));
这是app.module.ts
,但此代码适用于 RC5
您的服务:
let authService = new AuthService(new LocalStorage(), http);
authService.BASE_URL='you url goes here'
然后将其添加到providers数组
@NgModule({
imports: [
BrowserModule,
FormsModule,
],
declarations: [
AppComponent,
],
bootstrap: [
AppComponent
],
providers: [
{provide: AuthService, useValue: authService},
]
})