4

I am getting value using snapshot method but it is getting the value after "classes" in this case 20 but I need 33 path like getting

credits/33/classes/20 only 20 or credits/33/classes/ only null("")

Update: I found a solution to my question.

Now it is getting id properly. The mistake is accessing to element in the right child component, didn't work in child's MatDialog component within the Snapshot version.

constructor(private route: ActivatedRoute) {} 
 ngOnInit(): void {
   console.log(parseInt(this.route.snapshot.paramMap.get('id1')));

If your url has 2 Id values, you can use snapshot of route.parent

   console.log(parseInt(this.route.parent.snapshot.paramMap.get('id1')));
}
Rahimjon Rustamov
  • 246
  • 1
  • 3
  • 19

2 Answers2

14

your path in routing module will be

const appRoutes: Routes = [
{ path: 'credits/:id1/classes/:id2', component: YourComponent }];

suppose id1 is 33 and id2 is 20

the code will be: use ActivatedRoute instead of ActivatedRouteSnapshot

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

constructor(private route: ActivatedRoute) {

ngOnInit() {
this.route.params
      .subscribe(
        (params: Params) => {
          this.id1 = +params['id1'];
          this.id2 = +params['id2'];
          console.log(id1 + '' + id2);
        }
      );
    }
}
Nasreen Ustad
  • 1,564
  • 1
  • 19
  • 24
  • Could you give an explanation why you should use `ActivatedRoute` over `ActivatedRouteSnapshot`? I would only subscribe to `ActivatedRoute` if the params change **while** the component is still active and always needs the current params. So I'd say if you only need the params on the initialization of the component go for `ActivatedRouteSnapshot` – dewey Nov 09 '21 at 13:48
4

Create a route, in which will be routed to your component, and add it to your module.

const appRoutes: Routes = [
{ path: 'credits/:id1/classes/:id2', component: MyComponent },
{ path: 'credits/:id1', component: MyComponent }];

Then, you can use ActivatedRoute to get your params.

 export class MyComponent implements {
  id1: string;
  id2: string;

  constructor(private route: ActivatedRoute) { 
    this.id1 = this.route.snapshot.params['id1'];
    this.id2 = this.route.snapshot.params['id2'];
  }

}

StackBlitz here

John
  • 10,165
  • 5
  • 55
  • 71