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 ?
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.
Bring in the following rxjs subscription import.
import { Subscription } from 'rxjs/Subscription';
Add OnDestory to your Angular Core Import.
import { Component, OnDestroy, OnInit } from '@angular/core';
Add OnDestory to your export class.
export class DisplayComponent implements OnInit, OnDestroy {
Create a object property with a value of Subscription from rxjs under your export class for each subscription on the component.
myVariable: Subscription;
Set the value of your subscription to MyVariable: Subscriptions.
this.myVariable = this.rmanagerService.getRPDoc(books[i].books.id).subscribe(value => {});
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());
来源:https://stackoverflow.com/questions/41678356/router-navigate-does-not-call-ngoninit-when-same-page