【发布时间】:2019-08-02 11:22:58
【问题描述】:
我需要在我的 ngOnInit 中以 promise 的形式获取当前路由 id,并且在获得 id 值后,我想继续使用该 id。
我尝试过这样的事情:
var temp = this.route.snapshot.paramMap.get('id');
// and doing something with it here
和
this.route.params.toPromise().then(data => {
// doing something with it here
});
遗憾的是,它始终为空,即使我的网址类似于“localhost:4200/answer/1248523” 它需要发生在 ngOnInit 内部。 如何异步获取当前id?
我创建了一个导航栏来在我的 app.component.html 中的不同组件之间切换,基本上我想在组件之间切换/执行路由时保留 paramId。
<nav mat-tab-nav-bar mat-align-tabs="center">
<a mat-tab-link *ngFor="let link of navLinks" [routerLink]="link.link" routerLinkActive #rla="routerLinkActive"
[active]="rla.isActive">
{{link.label}}
</a>
</nav>
<router-outlet></router-outlet>
我的组件.ts
constructor(private router: Router,private route: ActivatedRoute) {
this.navLinks = [
{
label:'info',
link:'./information',
index:0
}, {
label: 'theme',
link:'./theme',
index:1
},
{
label: 'form',
link: './form',
index: 2
}, {
label: 'attach',
link: './attach',
index: 3
}, {
label: 'testSum',
link: './testSum',
index: 4
},
];
}
ngOnInit(): void {
var paramId = this.route.snapshot.paramMap.get('id');
this.router.events.subscribe((res) => {
if(this.router.url.indexOf("answer") !== -1) {
this.navLinks = [
{
label: 'Summary',
link: './answer/:id',
index: 0
}, {
label: 'Inbox',
link: ['./inbox',paramId],
index: 1
}
];
}
this.activeLinkIndex = this.navLinks.indexOf(this.navLinks.find(tab => tab.link === '.' + this.router.url));
});
}
我的路由也在寻找收件箱,答案是这样的:
{ path: 'answer/:id', component: AnswerSummaryComponent},
{ path: 'inbox/:id', component: InboxComponent}
所以基本上导航栏有一个标准的导航数组(信息、主题、表单、附件、testSum),但如果有人使用 (localhost:4200/answer....) 之类的链接访问站点/应用程序,它应该显示不同的导航。这工作得很好。
如果有人访问该网站,让我们说:localhost:4200/answer/123123 他会看到摘要组件,如果他导航到收件箱,我希望 url 保持“localhost:4200/inbox/123123”,但 url 更改为“localhost :4200/收件箱”。所以我想在链接(对象属性)本身中传递当前当前的 idParam。
【问题讨论】:
-
能否给个minimal reproducible example - 路由是如何配置的?另请注意the docs 推荐
paramMap,而不是params,并且Angular 基于可观察对象而不是承诺,用于异步操作。 -
你为什么需要它成为
Promise? -
添加了一个更好的例子。
标签: javascript angular asynchronous