使用AOT在角度库配置中使用window.location.origin



当我在角度库的forRoot({...})配置对象参数中传递window.location.origin并使用AOT编译时,它的值只是null。有没有一种方法可以在启用AOT的情况下将其值传递给我的角度库?

在谷歌上搜索了一些之后,我想也许需要用WINDOW设置注入令牌,然后在库端消费,但如果可能的话,我希望避免这种情况。我也可以只是硬编码的起源,但这是相当有限的。我想采用一种"先设置后忘记"的方法,因此我在图书馆中开辟了一个功能。

我的图书馆设置如下。

export class AppConfig {
origin: string;
}
...
export const APP_CONFIG_TOKEN = new InjectionToken<AppConfig>('APP_CONFIG_TOKEN');
...
@NgModule()
export class MyLibrary {
public static forRoot(config: AppConfig) {
return {
ngModule: MyLibrary,
providers: [
{
provide: APP_CONFIG_TOKEN,
useValue: config
}   
]
};
}

我正在库中的服务中消耗令牌的值

@Injectable()
export class MyService {
constructor(@Inject(APP_CONFIG_TOKEN) private config: AppConfig) { }
myOrigin(): string {
return this.config.origin; // expecting it to return a value like `http://localhost:4200` but it returns `null`
}
}

我正在我的AppModule中导入库,就像一样

@NgModule({
imports: [
MyLibrary.forRoot({ 
origin: window.location.origin // with AOT, this seems to be null
}) 
],
bootstrap: [AppComponent]
})
export class AppModule { }

AOT构建应用程序的各个部分,这样客户端就可以减少计算量。试着看看这个问题

https://github.com/angular/angular-cli/issues/10957

最新更新