简体   繁体   中英

Angular onInit doesn't get called when URL param changes

I have a path structure like this: /item/:id/editItem . In the component on the URL /item I have multiple buttons with an onclick function like this:

this.router.navigate([
      '/item/' + itemID + '/editItem'
    ]);

In the component on the URL /editItem I have a console log in the ngOninit that just say that it got started.

The problem is now, on the first click, I can see the console log in the console, but with every other click on other buttons no further console logs are displayed.

I am currently on the URL /item/car/editItem and get navigated with the function above to /item/house/editItem .

Does the onInit not get called because only a URL parameter changed? Do I need to subscribe the URL and just run my ngOnInit when the URL is changed?

ngOnInit()

A callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the directive is instantiated.

If you want to listen for route changes, you could add listener:

class MyClass {
  constructor(private router: Router) {
    router.events.subscribe((val) => {
        // see also 
        console.log(val instanceof NavigationEnd) 
    });
  }
}

For route changes, see: https://angular.io/guide/router#router-events

The ngOnInit method is run only when the component is created. With routes defined as you described, you should inject ActivatedRoute and subscribe to params (or paramMap ) change, like

constructor(private activatedRoute: ActivatedRoute) { //...

ngOnInit() {
    this.activatedRoute.params.subscribe(({ id }) => this.doSomethingWith(id));

You can reinstantiate your component, and therefore fire the OnInit hook on navigation by setting this parameter on your RouterModule while importing it in your parent module:

 RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM