Home > Enterprise >  Angular2 Filtering an http request
Angular2 Filtering an http request

Time:03-30

I wanted to get some advice and guidance regarding filtering an http request in Angular. I have a service that reaches out and grabs the data. The data is then used in an ngFor on the component.

Data Service Function to Grab the Data

getCycleStages(): Observable<StageContainer[]> {
  console.log('Starting stages');
  const url = this.stagesURL;
  return this.http.get<StageContainer[]>(url, this.httpOptions);
}

Then, on the component I import the service and subscribe to the http request.

Component Function to Subscribe to the Service Function

getStages(): void {
  this.BCS.getCycleStages()
  .subscribe({
    next: (response : any) => this.stages = response['value'],
    error: (e) => console.error(e),
    complete: () => console.log(this.stages)
  })
}

This all works, I get the data successfully. But I would like to filter the data I get from the http.get request. I have been searching online and trying different guides and looking at documentation. I have tried to filter in the service we seemed logical to me, as well as on the component, but I'm doing something (probably a lot) wrong.

Attempt 1 - Filter on the data service.

getCycleStages(): Observable<StageContainer[]> {
  console.log('Starting stages');
  const url = this.stagesURL;
  return this.http.get<StageContainer[]>(url, this.httpOptions).pipe(
    filter(val => val.sName = 'James')
  );
}

Attempt 2 - When I Subscribe on the Component

getStages(): void {
  this.BCS.getCycleStages()
  .subscribe({
    next: (response : any) => this.stages = response['value'].filter(val => val.sName = 'James'),
    error: (e) => console.error(e),
    complete: () => console.log(this.stages)
  })
}

Thanks so much for any help or guidance you can offer.

Have a great day!

CodePudding user response:

seems that you are not making a comparaison in your first solution :

getCycleStages(): Observable<StageContainer[]> {
  console.log('Starting stages');
  const url = this.stagesURL;
  return this.http.get<StageContainer[]>(url, this.httpOptions).pipe(
    filter(val => val.sName === 'James')
  );
}

It should be working fine then :D

And even better, if you want to reuse your service, pass an optional argument :

getCycleStages(filterQuery?: string): Observable<StageContainer[]> {
  console.log('Starting stages');
  const url = this.stagesURL;
  return this.http.get<StageContainer[]>(url, this.httpOptions).pipe(
    filter(val => val.sName === filterQuery)
  );
}
  • Related