0

I have created the app in Angular 7. In the navigation part, when the params change in browser url, page is not refreshing.

ex:

User clicked on disciplines menu item and the page url looks like http://localhost:4200/xxx/disciplines

user clicked on table row item in the disciplines page, url looks like http://localhost:4200/xxx/disciplines?disciplineId=1150

when user again click on the disciplines menu item, url is changing correctly in browser url like http://localhost:4200/xxx/disciplines but the page is not refreshing/reloaded.

Expert advise please?

klmuralimohan
  • 861
  • 4
  • 23
  • 44

1 Answers1

1

You need to use the ActivatedRoute from the Angular Router :

import { ActivatedRoute } from '@angular/router';

You just then have to inject it in your component's constructor:

constructor(private route: ActivatedRoute)

In your ngOnInit you'll just have to subscribe to the changes that happen on the route:

this.routeSubscription = this.route.params.subscribe((param: any) => {
this.id = param['disciplineId'];
this.yourSpecialFunction();
});

IMPORTANT: I always create a subscriber property:

import { Subscription } from 'rxjs';
...
...
export class YourComponent implements OnInit, OnDestroy {
private routeSubscription: Subscription

Make sure component implement OnDestroy and in the ngOnDestroy() method:

ngOnDestroy() { this.routeSubscription.unsubscribe(); }

You have to unsubscribe to every subscription in your app to avoid memory leaks.

For more subscription information, please refer to this Tomas Trajan's article: https://blog.angularindepth.com/the-best-way-to-unsubscribe-rxjs-observable-in-the-angular-applications-d8f9aa42f6a0

  • You don't need to unsubscribe the ActivatedRoute observable, but it's a good practice to have. https://stackoverflow.com/questions/41138081/do-i-have-to-unsubscribe-from-activatedroute-e-g-params-observables – Wen W Jun 17 '19 at 18:58