Angular 2: Changing route parameters, reloading the same page?

I have a route with a parameter when going to the / users / 123 page, where 123 is the parameter called by ngOnInit, I get my parameter, and I call my method to get the user.

However, when I am on this page and I click on the second link / users / 456, then ngOnInit is no longer called (since this page has already been created). Therefore, without ngOnInit, I cannot get the route parameter and I cannot call my method to get the user.

If I go to / users / 123, then in / home, then in / users / 456, it works explicitly.

What do I need to use to make sure that the function that receives this parameter and receives the user is ALWAYS called, even if I'm already on the same page?

+6
source share
4 answers

You can use the route.params subscriber to listen for a parameter change.

 import { ActivatedRoute } from '@angular/router'; export class DemoPage { constructor(private _route: ActivatedRoute) { } ngOnInit() { this._route.params.forEach(params => { let userId = params["userId"]; //call your function, like getUserInfo() }) } } 
+9
source

Params is observable. Therefore, you only need to subscribe once to the observed, and each time the parameters change, you receive a notification.

 constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.params .switchMap((params: Params) => /* load your user eg getUser(params['id']) */) .subscribe(user => this.user = user); } 

You also need to import ActivatedRoute and Params

 import { ActivatedRoute, Params } from '@angular/router'; 
+4
source

OnInit is called only once when the directive is instantiated.

For viewing route options, use ActivatedRoute .

 constructor(private route: ActivatedRoute) { } ngOnInit(): void { this.route.params.forEach((params: Params) => { console.log(params); // Your params called every change }); } 

Do not forget to import:

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

Learn more about OnInit: OnInit - ts - API

Learn more about ActivatedRoute: ActivatedRoute - ts - API

+1
source

Ok, sorry guys, I called to get a user outside of the activated Route callback.

It is right:

 import { ActivatedRoute } from '@angular/router'; export class DemoPage { constructor(private _route: ActivatedRoute) { } ngOnInit() { this._route.params.forEach(params => { let userId = params["userId"]; getUserInfo(userId); }); } } 

What I've done:

 import { ActivatedRoute } from '@angular/router'; export class DemoPage { constructor(private _route: ActivatedRoute) { } ngOnInit() { var userId = ""; this._route.params.forEach(params => { userId = params["userId"];          }); getUserInfo(userId) } } 
0
source

Source: https://habr.com/ru/post/1013630/


All Articles