Dou*_*eri 2 typescript angular angular-router
我不确定这是否是实现此目的的最佳方法。如果您有其他意见请分享。
我必须实现一个多收件箱系统,用户可以将多封电子邮件按不同的收件箱分组。
例如:http://localhost/inbox/personal/将在收件箱中显示电子邮件列表personal,http://localhost/inbox/business/3将在收件箱中显示电子邮件列表business,并突出显示带有 id 的电子邮件:3
路线如下:
const routes: Routes = [
{
path: '',
pathMatch: 'full',
redirectTo: 'personal' // redirect to personal inbox
},
{
path: ':inbox',
component: InboxContentComponent, // list of emails in :inbox
children: [
{
path: '',
component: InboxNoSelectedEmailComponent, // no email selected
},
{
path: ':id',
component: InboxSelectedEmailComponent, // show selected email content
}
]
}
];
Run Code Online (Sandbox Code Playgroud)
我的问题是InboxContentComponent. 我需要检测收件箱何时更改以及是否选择了电子邮件
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.route.paramMap.subscribe(inbox => {
console.log('inbox', inbox);
});
}
Run Code Online (Sandbox Code Playgroud)
仅当收件箱更改时才会发出事件,而当电子邮件更改时不会发出事件。有没有办法检测子路由参数何时发生变化?
this.route.firstChild.paramMap.subscribe();仅当在组件初始化时路由有第一个子级时,这样做才有效。如果路线是这样的http://localhost/inbox/business/话this.route.firstChildnull
关于解决方案,我认为是定义这样的路线
{
path: ':inbox/:id',
component: InboxContentComponent
}
Run Code Online (Sandbox Code Playgroud)
然后检查InboxContentComponent是否:id设置
有任何想法吗?
为了解决这类问题,我会监听路由器事件并检索我想要的内容。像这样的东西:
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { filter, map, mergeMap, tap } from 'rxjs/operators';
// ...
constructor(
// ...
private activatedRoute: ActivatedRoute,
private router: Router
) {
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map((route) => {
while (route.firstChild) route = route.firstChild;
return route;
}),
mergeMap((route) => route.paramMap),
tap(
paramMap => console.log('ParamMap', paramMap)
)
).subscribe(
(paramAsMap) => // Get the params (paramAsMap.params) and use them to highlight or everything that meet your need
)
}
Run Code Online (Sandbox Code Playgroud)
您可以根据您的需要进行调整。参数?突出显示:无突出显示。
| 归档时间: |
|
| 查看次数: |
6289 次 |
| 最近记录: |