【问题标题】:Wrong parameter from URL after navigating in Angular在 Angular 中导航后来自 URL 的参数错误
【发布时间】: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


【解决方案1】:

params.map()

您可以在route.params 上致电map()

另外,因为route.paramsobservable,所以将其分配给Subscription。看这里:

sub: Subscription;
constructor(private route: ActivatedRoute) {}

ngOnInit() {    
        this.sub = this.route.params
            .map(params => params['id'])
            .subscribe(id => this.id = id);
    }

另一个结果是调用router.navigateByUrl() 而不是router.navigate()

【讨论】:

  • 不。它没有帮助。还是一样的问题
  • 如果我在上述代码的订阅中添加其余的 ngOnInit 代码,那么它应该可以正常工作。
猜你喜欢
  • 2019-04-30
  • 2022-11-04
  • 2018-05-19
  • 1970-01-01
  • 2019-05-18
  • 1970-01-01
  • 2021-10-06
  • 2016-03-19
相关资源
最近更新 更多