8

I want to be able to change data on my page based on the URL route, i.e. test/1 gets me data set 1, test/2 gets me data set 2. However if i am already on test/1 and try to navigate to test/2 (and vice versa) using router navigate, it changes the url but that's it, nothing else gets triggered.

I have following definition for my route:

const routes: Routes = [
  {
    path: 'test',
    children: [
      {
        path: ':id',
        component: TestComponent
      },
      { path: '**', redirectTo: '', pathMatch: 'full' }
    ]
  },
];

TS Component:

value: any;

constructor(private router: Router, private, private route: ActivatedRoute) { 
   this.value = this.route.snapshot.params.id;
}

goToPage(value: any) {
    this.router.navigate(['/test', value]);
}

my html component:

{{value}}

<button (click)="goToPage(1)">One</button>
<button (click)="goToPage(2)">Two</button>

I've also tried adding { onSameUrlNavigation: 'reload' } to RouterModule.forRoot, still doesn't do anything.

NOTE: Problem is not to get the parameter, the problem is the refresh of the page that has to take place to trigger all processes associated with the new parameter.

Aeseir
  • 7,754
  • 10
  • 58
  • 107

5 Answers5

11

Option 1: Listen to route changes and initialize page

constructor(private router: Router, private, private route: ActivatedRoute) {
   this.value = this.route.snapshot.params.id; // for first entry
   route.params.subscribe(val => {
     this.value = this.route.snapshot.params.id;
     // put the code to initialize the page
   });

}

Option 2: Reinitialize the page on route navigation

goToPage(value: any) {
    this.router.routeReuseStrategy.shouldReuseRoute = function () {
        return false;
    }
    this.router.onSameUrlNavigation = 'reload';
    this.router.navigate(['/test', value]);
}
Jp Vinjamoori
  • 1,173
  • 5
  • 16
6

Resolved the problem by implementing the following code:

    this.router.navigate(['/test', value])
        .then(() => {
          window.location.reload();
        });
Aeseir
  • 7,754
  • 10
  • 58
  • 107
  • 1
    Lovely stuff over here... I spent 3 hours trying to figure out... And the solution is so dope. Just to simply Go with the reload functionality to the next page... #Claps – Neo Sono Jun 18 '22 at 18:09
  • 1
    YEAAAAAAAAAAAAAAAAAAAAA – Gaspa79 Mar 06 '23 at 14:25
  • Well. because the alternative is to subscribe to a change event of the active route or something. Btw reloading a while Angular application is NOT the right way to do this.. Since this will definitely cause performance issues on the client-side. – Melroy van den Berg May 20 '23 at 20:46
  • Terrible user experience. Does work though. – MadMac Aug 10 '23 at 05:17
2

For it to be able to refresh the data, this piece of code this.value = this.route.snapshot.params.id should be called in ngOnInit() in this manner:

  ngOnInit() {
    this.activatedRoute.params.subscribe(
      param => {
        this.value = param['id']
        }
      }
    );
  }
sephoro
  • 150
  • 10
0

Instead of getting params from this.value = this.route.snapshot.params.id you can subscribe the paramMap and get the id

this.route.paramMap.subscribe(
  (params: ParamMap) => {
    const id = params.get('id');

    // call your api etc to get the record against new id
  }
);
Kamran Khatti
  • 3,754
  • 1
  • 20
  • 31
  • Yep already across that method but how does that solve refresh of the page problem? – Aeseir Aug 13 '21 at 03:50
  • @Aeseir it subscribe each time when route change and you will have a new route value, I believe I posted this answer first so you should have accept my attempt :) anyways you can upvote though – Kamran Khatti Aug 17 '21 at 07:36
  • @KamranKhatti you need to add this piece of code to the constructor and not to ngOnInit() – Melroy van den Berg May 20 '23 at 20:47
0

My full solution using the subscribe() method, in TS with Angular:

import { Component, OnInit } from '@angular/core'
import { Params, Router } from '@angular/router'
import { ActivatedRoute } from '@angular/router'
import { Location } from '@angular/common'
import { UserService } from '../user.service'
import { User } from '../user.model'
import { Observable, of } from 'rxjs'

export class YourComponent implements OnInit {
    user$: Observable<User> = of({} as User)
    id: number | undefined = 0

    constructor(
        private router: Router,
        private route: ActivatedRoute,
        private userService: UserService,
        private location: Location
    ) {
        this.id = this.route.snapshot.params.id
        // Listen on change event for ID parameter
        this.route.params.subscribe((params: Params) => {
          this.id = params['id']
          this.loadDetails() // triggered when pressing the button
        });
    }

    ngOnInit() {
        this.loadDetails() // Initial load during page load
    }

    changePage(userId: number) {
        this.router.navigate(['user/detail', userId])
    }

    private loadDetails() {
        const id = (this.id) ? +this.id : 0 // Zero should fail
        this.user$ = this.userService.getOne(id) // Your service or API or...
    }
}

HTML template:

<button mat-raised-button type="submit" (click)="changePage(user.id)">BLabla</button>
Melroy van den Berg
  • 2,697
  • 28
  • 31