Home > Software engineering >  Is it possible to map multiple query string parameters to a property of an Angular service component
Is it possible to map multiple query string parameters to a property of an Angular service component

Time:07-02

Question: Is it possible to retrieve a collection of query string values and assign them to a property of type Filter in a service component class?

interface Filter{
    title?: string;
    genreId?: number;
    inCinemas?: boolean;
    upcomingReleases?: boolean;
}

rather than doing the following tedious, error prone of retrieval and assignment?

constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
  this.route.paramMap.subscribe({
    next: params => this.title = params.get('title'),
    error: e => console.log(e)
  });
  this.route.paramMap.subscribe({
    next: params => this.genreId = params.get('genreId'),
    error: e => console.log(e)
  });
  this.route.paramMap.subscribe({
    next: params => this.inCinemas = params.get('inCinemas'),
    error: e => console.log(e)
  });
  this.route.paramMap.subscribe({
    next: params => this.UpcomingReleases = params.get('upcomingReleases'),
    error: e => console.log(e)
  });
}

CodePudding user response:

You could make it very simple, as long as your class properties are the same name as the query string keys, you can do something like this:

export class SearchPageComponent {
  title = '';
  genreId = '';
  inCinemas = '';
  upcomingReleases = '';
 
  constructor(private readonly route: ActivatedRoute) { }

  ngOnInit() {
    // Don't forget to unsubscribe
    this.route.queryParams.pipe(
      // Send each query param as a string to the next pipe individually
      concatMap(i => Object.entries(i)),
      // filter only continue with the current key if the property exists in the class
      filter(([key]) => key in this),
      // Assign the item to the property
      tap(([key, val]) => (this as any)[key] = val)
    ).subscribe(i => console.log(i));
  }
}
  • Related