我需要做的是动态设置<base href="" />
中的index.html
标记,或者动态设置APP_BASE_HREF
我不确定如何在index.html
上设置任何内容,因为它似乎都是静态文本。
我已经尝试过以下操作来设置APP_BASE_HREF
,但是我仍然收到以下错误消息:
Unhandled Promise rejection: url.replace is not a function ; Zone: <root> ; Task: Promise.then ; Value: TypeError: url.replace is not a function
at _stripIndexHtml (common.js:282)
at new Location (common.js:149)
at _createClass (core.js:19829)
at _createProviderInstance (core.js:19801)
at initNgModule (core.js:19734)
at new NgModuleRef_ (core.js:20461)
at createNgModuleRef (core.js:20450)
at Object.debugCreateNgModuleRef [as createNgModuleRef] (core.js:22281)
at NgModuleFactory_.push../node_modules/@angular/core/fesm5/core.js.NgModuleFactory_.create (core.js:23009)
at core.js:16622 TypeError: url.replace is not a function
at _stripIndexHtml (http://localhost:3577/vendor.js:25317:16)
at new Location (http://localhost:3577/vendor.js:25184:56)
at _createClass (http://localhost:3577/vendor.js:80131:20)
at _createProviderInstance (http://localhost:3577/vendor.js:80103:26)
at initNgModule (http://localhost:3577/vendor.js:80036:32)
at new NgModuleRef_ (http://localhost:3577/vendor.js:80763:9)
at createNgModuleRef (http://localhost:3577/vendor.js:80752:12)
at Object.debugCreateNgModuleRef [as createNgModuleRef] (http://localhost:3577/vendor.js:82583:12)
at NgModuleFactory_.push../node_modules/@angular/core/fesm5/core.js.NgModuleFactory_.create (http://localhost:3577/vendor.js:83311:25)
at http://localhost:3577/vendor.js:76924:43
这是我尝试过的:
export function startupServiceFactory(settingsService: SettingsService): Function {
return async () => {
const ombi = await settingsService.getOmbi().toPromise()
const baseUrl = ombi.baseUrl.length > 0 ? ombi.baseUrl : "/";
return baseUrl;
}
}
@NgModule({
imports: [
// snip
],
declarations: [
// snip
],
providers: [
SettingsService,
{
provide: APP_BASE_HREF,
useFactory: startupServiceFactory,
deps: [SettingsService],
multi: true
}
],
bootstrap: [AppComponent],
})
export class AppModule { }
如上所示,我试图在服务器上调用一个返回对象的API,然后有一个baseUrl
属性,我想将其设置为APP_BASE_HREF
>
我知道可以在构建期间进行设置,但是我开发的网站允许用户自己进行设置,并且值存储在数据库中(用户可以自行安装应用程序)。
答案 0 :(得分:0)
我认为您不能使用工厂提供程序返回 APP_BASE_HREF
(github issue)
一种可能的解决方法是在引导应用程序之前进行远程调用以获取数据,将动态值存储在某处(在下面示例中的 window
中)并在提供 APP_BASE_HREF
时重用它
main.ts
fetch('https://yourbackendconfigserver.com')//Just an example of API call
.then(response => response.json())
.then(json =>{
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
}
);
app.module.ts
export function baseHRefFactory(): Function {
return window['baseHref'];
}
@NgModule({
imports: //...
declarations: //...
providers:[
{
provide: APP_BASE_HREF,
useFactory: baseHRefFactory,
}
],
bootstrap: [ AppComponent ]
})
export class AppModule { }