我正在使用Angular 2,我有以下问题 .
在几个按钮上,我有一个重定向功能,可以移动到另一个页面 .
HTML
<button type="button" class="btn btn-primary btn-sm mb-xs" *ngFor="let pl of results;let i=index" (click)="onButtonClick(pl.pl_id)">{{i+1}}</button>
Then on my component I have those functions:
ngOnInit() {
this.sub = this._route.params.subscribe(params => {
this.id = +params['id'];
});
...
...
}
onButtonClick(id) {
this._router.navigate(['/app/data', id]);
this.ngOnInit();
}
我在导航后调用ngOnInit的原因是,如果不这样做,则URL会更改,但页面内容保持不变 .
所以,这里的问题是 ngOnInit
get是前一个url的参数,而不是 navigate
之后的参数 .
例如,我在url /app/data/1
上,然后单击带有 onButtonClick(2)
函数的按钮 .
URL更改为 /app/data/2
,但内容是来自 /app/data/1
的内容 . 如果我再次点击相同的按钮,它会获得正确的内容 . 所有其他按钮也一样 .
我的想法是 navigate
需要一些时间来更新URL并且 ngOnInit
更快并且从当前URL而不是新URL获取参数 .
任何的想法?
Edit: 我从另一个问题中找到了这个答案但没有修复它:
因此,例如,从/ component / 1导航到/ component / 2,其中url映射到相同的组件(但具有不同的参数)将导致路由器在导航到/ component / 1时实例化Component的实例,然后在导航到/ component / 2时重新使用该实例 . 基于你遇到的情况 .
至于路由配置,那些是特定组件的模块 . 如果您需要更多,请告诉我 .
export const routes = [
{path: 'archive', component: archivedContests, pathMatch: 'full', canActivate: [LoggedInGuard]},
{path: ':id', component: editContest, pathMatch: 'full', canActivate: [LoggedInGuard]},
{path: '', component: Contests, pathMatch: 'full', canActivate: [LoggedInGuard]}
];
1 回答
params.map()
您可以在
route.params
上拨打map()
.此外,由于
route.params
是observable
,因此将其分配给Subscription
. 看看这里:另一个结果是调用
router.navigateByUrl()
而不是router.navigate()
;