Home > Mobile >  How to get the angular route params values in the url?
How to get the angular route params values in the url?

Time:12-13

I have Angular route: /Chapter/:chapterId/Section/:sectionId.

And a URL: http://server.com/Chapter/1/Section/2?search=moby.

How to extract the params and query string together in Angular to something like this: {chapterId:'1', sectionId:'2', search:'moby'}?

CodePudding user response:

Just a case of pulling the info from ActivatedRoute

params$: Observable<{chapterId: string, sectionId: string, search: string}> = of()

// Inject the ActivatedRoute service into your component
constructor(private route: ActivatedRoute) {}

ngOnInit() {
// Combine the route parameter and query parameter observables
  this.params$ = combineLatest([
    this.route.paramMap,
    this.route.queryParamMap
  ]).pipe(
    // Use the map operator to transform the observables into an object
    map(([paramMap, queryParamMap]) => ({
      chapterId: paramMap.get('chapterId'),
      sectionId: paramMap.get('sectionId'),
      search: queryParamMap.get('search')
    }))
  );
}

CodePudding user response:

// Routed component only
export class PageComponent implements OnInit {
      private readonly route = inject(ActivatedRoute);
    
      ngOnInit() {
        this.route.params.subscribe(console.log); // {chapterId: '1', sectionId: '2'}
        this.route.queryParams.subscribe(console.log); // {search: 'moby'}
      }
    }
  • Related