【发布时间】:2017-07-22 20:57:06
【问题描述】:
我正在使用 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>
然后在我的组件上我有这些功能:
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 获取的是前一个url 的参数,而不是navigate 之后的参数。
例如,我在 url /app/data/1 上,然后单击功能为 onButtonClick(2) 的按钮。
URL 更改为/app/data/2,但内容是来自/app/data/1 的内容。如果我再次单击同一个按钮,它将获得正确的内容。所有其他按钮都一样。
我的想法是navigate 需要一些时间来更新 URL,ngOnInit 更快,并且从当前 URL 而不是新 URL 获取参数。
有什么想法吗?
编辑: 我从另一个问题中找到了这个答案,但没有解决它:
因此,例如,从 /component/1 导航到 /component/2,其中 url 映射到同一个组件(但具有不同的参数)将导致路由器在您实例化 Component 实例时导航到 /component/1,然后在导航到 /component/2 时重新使用同一个实例。根据您所描述的内容(ngOnInit 只被调用一次),似乎这就是您遇到的情况。
至于路由配置,这些是特定组件的模块。如果您需要更多,请告诉我。
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]}
];
【问题讨论】:
-
控制台有错误吗?
-
@ArmanAsghari 什么都没有。我只是在“网络”选项卡上看到了错误的链接,稍后我使用之前的 URL 参数调用
ngOnInit。 -
您的组件是否实现
OnInit?我的意思是手动调用this.ngOnInit()的目的是什么? -
是的。我的组件实现了
OnInit,但正如我所说,如果我不把this.ngOnInit()放在那里,当URL 随导航发生变化时,内容不会更新。 -
这个问题是关于路由的,但是你的路由配置在哪里???
标签: angular