如何更改和加载取决于angular中url参数的配置文件



我的问题是我有两个配置文件,我想在页面加载时更改配置文件,这取决于url参数?

现在我已经做了一些类似的事情:

配置加载程序服务.ts

@Injectable()
export class ConfigLoaderService {     
constructor(private injector: Injector, private http?: HttpClient) { }

public get router(): Router {
return this.injector.get(Router);
}

url : string;
link : string;
initialize() {
this.url = this.router.url;
if (this.url == "/demo")
{
this.link = 'assets/demoConfig.json'
}
else {
this.link = 'assets/config.json'
}
return this.http.get<ModeActivation>(this.link)
.pipe(tap((response: ModeActivation) => {

app.module.ts

providers: [DemandeClass,
ConfigLoaderService,
{
provide: APP_INITIALIZER,
deps: [
ConfigLoaderService
],
multi: true,
useFactory: PreloadFactory
}
],

有了这个,我没有得到错误,但

this.router.url

总是"/"即使我进入

localhost:4200/demo

所以它进入了我的第二个条件!我做错了什么?有人请

这是因为当您访问路由器时,应用程序仍在初始化,路由器尚未在内部导航到您的url。

作为证明,您可以在配置服务中检查this.router.navigated的值,该值将为false(在完成一次导航后为true,请参阅文档(

解决方案

您可以使用window.location.pathname而不是使用路由器

initialize() {
this.url = window.location.pathname;// instead of this.router.url;
console.log("Has router navigated?", this.router.navigated) //will be false
console.log('current url', this.url); //correct url

这是一个堆叠litz演示

您能在路由数据中添加配置吗?

{
path: 'path',
component: Component,
data: myConfigForThsiRoute,
},

最新更新