Router Navigate does not call ngOnInit when same p

2019-01-13 20:29发布

I am calling router.navigate on same page with some query string parameters. In this case, ngOnInit() does not call. Is it by default or do I need to add anything else ?

6条回答
对你真心纯属浪费
2楼-- · 2019-01-13 20:56

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.

查看更多
太酷不给撩
3楼-- · 2019-01-13 20:59

You could adjust the reuseStrategy on the Router.

constructor(private router: Router) {
    // override the route reuse strategy
    this.router.routeReuseStrategy.shouldReuseRoute = function() {
        return false;
    };
}
查看更多
Root(大扎)
4楼-- · 2019-01-13 21:01

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.

查看更多
Bombasti
5楼-- · 2019-01-13 21:11

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)

查看更多
放我归山
6楼-- · 2019-01-13 21:16

Maybe you actually 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'})] })
查看更多
等我变得足够好
7楼-- · 2019-01-13 21:17

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(); }

查看更多
登录 后发表回答