【发布时间】:2021-08-30 08:17:49
【问题描述】:
我一直在使用 SCAM(单组件 Angular 模块)方法,但在将 injection token 从父模块传递到子模块时遇到了问题。
我有一个 ScamService,其中注入了 httpClient 和 baseUrl:
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Injectable, Inject, NgModule, ModuleWithProviders } from '@angular/core';
import { BASE_URL } from './injection.tokens';
@Injectable()
export class ScamService {
constructor( @Inject(BASE_URL) private baseUrl, private httpClient: HttpClient ) {}
public getData() {
return this.httpClient.get(`${this.baseUrl}/rest-of-endpoint`);
}
}
@NgModule({
imports: [HttpClientModule]
})
export class ScamServiceModule {
public static forRoot(baseUrl): ModuleWithProviders<ScamServiceModule> {
return {
ngModule: ScamServiceModule,
providers: [{
provide: BASE_URL,
useValue: baseUrl
}]
};
}
}
要向模块提供 BASE_URL 令牌,我需要创建返回 ModuleWithProviders 的静态方法。在那里我可以为令牌分配一个值。没关系。
接下来,我想在一个组件中使用该服务,所以我将 ScamServiceModule 导入到 ScamComponentModule 中:
import { Component, ModuleWithProviders, NgModule } from '@angular/core';
import { ScamService, ScamServiceModule } from './scam.service';
@Component({//...})
export class ScamComponent {
constructor(private scamService: ScamService) {}
}
@NgModule({
imports: [
ScamServiceModule.forRoot(
`The url I would like to pass is not in the environments,
I need to take it from forRoot of ScamComponentModule`
)
]
})
export class ScamComponentModule {
public static forRoot(baseUrl): ModuleWithProviders<ScamComponentModule> {
// how to tell ScamServiceModule what the value of baseUrl is?
}
}
现在我需要为其提供基本网址。所以我应该调用 ScamServiceModule.forRoot('some-url')。如果我知道组件级别的 url,那就太好了。
但是url需要通过ScamComponentModule的forRoot方法传递。
你对如何传递baseUrl有什么建议吗?
提前谢谢你!
【问题讨论】:
标签: angular dependency-injection angular-module injection-tokens