更新时间:2023-02-21 17:49:52
所以,有人问我如何解决此问题,
so, someone was asking me how i solved this issue,
首先,我添加了一条新路线作为所有其他路线的后备路线,例如:
first i added a new route as a fallback to all other routes, something like this:
{path: ':url', loadChildren: './fallback/fallback.module#FallbackModule'}
然后在fallbackComponent内部,我们根据路由器导航结束事件上的url决定加载哪个模块.
then inside fallbackComponent we decide what module to load based on the url on router navigation end event.
在我的情况下,如果网址是/@ somestring,我想加载profileComponent并调用一些API
in my case, if the url was /@somestring, i wanted to load the profileComponent and call some APIs
ngOnInit() {
this.router.events.filter(event => event instanceof NavigationEnd)
.subscribe((event) => {
this.parseUrl(this.router.url);
});
}
parseUrl(url: string) {
let data = {};
let parts: string[] = url.split('/');
parts = parts.filter((item) => !!item);
if (parts[0] && parts[0].indexOf('@') === 0) {
data['component'] = 'profile';
data['username'] = parts[0].replace('@', '');
}
this.viewData = data;
}
并在模板中:
<template [ngIf]="viewData && viewData['component'] == 'profile'">
<user-profile
[title] = "viewData['view']"
[username] = "viewData['username']"
></user-profile>
</template>
还值得一提的是,我们还必须重写DefaultUrlSerializer.serialize才能禁用对网址中特殊字符(@)的自动编码.
also worth to mention that we also had to override DefaultUrlSerializer.serialize to disable auto encoding for special characters (@) in urls.