Search code examples
angularangular2-routing

angular navigate to the same route with different parameter


Although this question seems to have popped up before, I can't find an answer that works for me, as the router seems to have changed a lot over the lifetime of angular.

In angular 5 I have a component where I wish to edit a user. I navigate to that component with the following code:

this.router.navigate(['editsingleuser',user.username])

Which will send me to /editsingleuser/bob

Then, from within that component I can also click on a button to edit my own user details, which uses the following code:

this.router.navigate(['editsingleuser',this.user.sub])

Which should send me to /editsingleuser/joe, but does not

Is there a parameter that I can add to the router.navigate that forces it to load the route, as it seems to be doing some kind of caching?

I have also tried using

[routerLink]="['editsingleuser',user?.sub]" 

which also has the same issue


Solution

  • The answer to this problem was that I had to subscribe to the route parameter in my EditSingleUser component, and use this value when I fetched the data for the page

    In ngOnInit()

    this.route.params
      .switchMap((p: Params)=>{
          let usr = p['username']; //read the username route parameter
          return this.apiService.getUser(usr)}      //call getUser with that parameter
            )
      .subscribe(data=> {
        this.user= data
        console.log("data :" + JSON.stringify(data));
        this.setupFormData();          //use the resulting data to set up the form
      })