【发布时间】:2020-05-25 04:55:42
【问题描述】:
我有一个 Angular 9 (9.1.4) 项目,并且有一个 BASE_URL 的自定义工厂提供程序(该项目基于 .NET Core Angular 模板)
// main.ts
export function getBaseUrl() {
return document.getElementsByTagName('base')[0].href;
}
const providers = [
{ provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] }
];
platformBrowserDynamic(providers).bootstrapModule(AppModule)
.catch(err => console.error(err));
如果我想在类中使用 BASE_URL,超级简单,我可以要求将它注入到构造函数中
export class SomeService {
constructor(
private _httpClient: HttpClient,
@Inject('BASE_URL') private _baseUrl: string // here we go
) { }
它按预期工作。到目前为止一切顺利...
我最近在应用程序中添加了一个APP_INITIALIZER,因此我可以预先从服务器加载一些配置。这是通过使用工厂函数注册提供者来完成的,也可以将依赖项注入其中。
但是,由于某种原因,使用@Inject 的简单方法在那里不起作用:
// app.module.ts
@NgModule({
// other stuff
providers: [
SomeService, // here the @Inject works
{
provide: APP_INITIALIZER,
useFactory: (httpClient: HttpClient, @Inject('BASE_URL') baseUrl: string) => {
// httpClient is OK, but baseUrl is undefined
// app init implementation
},
deps: [HttpClient],
multi: true
}],
因为在运行时未定义 baseUrl。
我可以让它工作的唯一方法是从 @angular/core 注入 Injector:
{
provide: APP_INITIALIZER,
useFactory: (httpClient: HttpClient, injector: Injector) => {
cont baseUrl = injector.get('BASE_URL'); // works, but deprecated
// app init implementation
},
deps: [HttpClient, Injector],
multi: true
}
但问题在于 get 方法的弃用警告(自 v4.0.0 起已弃用)。
让这种工厂注入工作的正确方法是什么?
【问题讨论】:
标签: angular