Router Navigate在同一页面时不会调用ngOnInit

问题描述 投票:42回答:7

我在同一页面上使用一些查询字符串参数调用router.navigate。在这种情况下,ngOnInit()不会打电话。它是默认还是我需要添加其他内容?

angular navigateurl ngoninit
7个回答
77
投票

你可以注入ActivatedRoute并订阅params

constructor(route:ActivatedRoute) {
  route.params.subscribe(val => {
    // put the code from `ngOnInit` here
  });
}

路由器仅在导航到不同路径时销毁并重新创建组件。如果仅更新路径参数或查询参数但路径相同,则不会销毁和重新创建组件。

强制重新创建组件的另一种方法是使用自定义重用策略。另见Angular2 router 2.0.0 not reloading components when same url loaded with different parameters?(似乎没有太多可用的信息,但如何实现它)


60
投票

您可以在路由器上调整reuseStrategy。

constructor(private router: Router) {
    // override the route reuse strategy
    this.router.routeReuseStrategy.shouldReuseRoute = function() {
        return false;
    };
}

4
投票

也许你真的需要重新加载页面?这是我的解决方案:我已经更改了@NgModule(在我的案例中,在app-routing.module.ts文件中):

@NgModule({
  imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})] })

1
投票

在创建实例时,将调用NgOnInit一次。对于相同的实例,NgOnInit将不再被调用。为了调用它,有必要销毁创建的实例。


1
投票

此问题可能来自于您未使用ngOnDestroy终止订阅的事实。这是如何完成的。

  1. 引入以下rxjs订阅导入。 import { Subscription } from 'rxjs/Subscription';
  2. 将OnDestory添加到Angular Core Import。 import { Component, OnDestroy, OnInit } from '@angular/core';
  3. 将OnDestory添加到导出类。 export class DisplayComponent implements OnInit, OnDestroy {
  4. 对于组件上的每个订阅,在导出类下为rxjs创建一个值为Subscription的对象属性。 myVariable: Subscription;
  5. 将订阅的值设置为MyVariable:订阅。 this.myVariable = this.rmanagerService.getRPDoc(books[i].books.id).subscribe(value => {});
  6. 然后在ngOninit下面放置ngOnDestory()生命周期钩子并输入您订阅的取消订阅声明。如果您有多个,请添加更多ngOnDestroy() { this.myVariable.unsubscribe(); }

0
投票

考虑将ngOnInit中的代码移动到ngAfterViewInit中。后者似乎在路由器导航上被调用,在这种情况下应该会帮助你。


-2
投票

当您想要路由器在同一页面上导航并想要调用ngOnInit()时,您也可以这样做,例如,

this.router.navigate(['category / list',category])。then(()=> window.location.reload());

© www.soinside.com 2019 - 2024. All rights reserved.