Jon Sud
Jon Sud

Reputation: 11671

How to get the angular route params values in the url?

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'}?

Upvotes: 0

Views: 78

Answers (1)

Andrew Allen
Andrew Allen

Reputation: 8062

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')
    }))
  );
}

Upvotes: 1

Related Questions