Router Navigate does not call ngOnInit when same page

和自甴很熟 提交于 2019-11-27 03:12:10
Günter Zöchbauer

You can inject the ActivatedRoute and subscribe to params

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

The router only destroys and recreates the component when it navigates to a different route. When only route params or query params are updated but the route is the same, the component won't be destroyed and recreated.

An alternative way to force the component to be recreated is to use a custom reuse strategy. See also Angular2 router 2.0.0 not reloading components when same url loaded with different parameters? (there doesn't seem to be much information available yet how to implement it)

You could adjust the reuseStrategy on the Router.

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

Do you probably need reloading page? This is my solution: I've changed my @NgModule (in app-routing.module.ts file in my case) :

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

NgOnInit would be called once when an instance is created. For the same instance NgOnInit won't be called again. In order to call it it is necessary to destroy the created instance.

This problem is likely coming from that fact that you are not terminating your subscriptions using ngOnDestroy. Here is how to get'ter done.

  1. Bring in the following rxjs subscription import. import { Subscription } from 'rxjs/Subscription';

  2. Add OnDestory to your Angular Core Import. import { Component, OnDestroy, OnInit } from '@angular/core';

  3. Add OnDestory to your export class. export class DisplayComponent implements OnInit, OnDestroy {

  4. Create a object property with a value of Subscription from rxjs under your export class for each subscription on the component. myVariable: Subscription;

  5. Set the value of your subscription to MyVariable: Subscriptions. this.myVariable = this.rmanagerService.getRPDoc(books[i].books.id).subscribe(value => {});

  6. Then right below ngOninit place the ngOnDestory() life cycle hook and put in your unsubscribe statement for your subscription. If you have multiple, add more ngOnDestroy() { this.myVariable.unsubscribe(); }

Consider moving the code you had in ngOnInit into ngAfterViewInit. The latter seems to be called on router navigation and should help you in this case.

When you want to router navigate on the same page and want to call ngOnInit(), so you do like that e.g,

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!