3

I am new to Angular and Observable. I want to apply filter on array of objects. This is how my code looks. .

getReport() gets all reports.

 getReports(): Observable<IReport[]>  {
    console.log("in get Reports Service Call");
    return this._http.get<IReport[]>(this.URL)
      .pipe(
        tap(data => console.log('All Data Retrieved - ' + JSON.stringify(data))),
        catchError(this.handleError));
  }

I am trying to write another method that can filter based on report name and give me array of IReport. This is what I have now.

 getReportDetails(name : string) : Observable<IReport[]>
  {
    return this.getReports().pipe(
      map((reports : IReport[]) => reports.find(p => p.reportName === name))
    );
  }

I am getting error as

Type 'Observable<IReport>' is not assignable to type 'Observable<IReport[]>'.

Here is IReport interface with 5 properties.

export interface IReport {
    date: Date;
    reportName: string;
    reportLink: string;
    reportStatus: string;
    region: string;
  }

What am I doing wrong? Thanks all.

3
  • Which method gives you the error when executed, getReports() or getReportDetails(name)? Commented Sep 10, 2018 at 18:24
  • getReportDetails(). Olivier helped me . I am good. Thanks Commented Sep 10, 2018 at 18:25
  • Oh.. great! I did not see Commented Sep 10, 2018 at 18:26

3 Answers 3

7

I think it should be

map((reports : IReport[]) => reports.filter(p => p.reportName === name))

instead of

map((reports : IReport[]) => reports.find(p => p.reportName === name))

find will return the first IReport that matches the condition p.reportName === name

Sign up to request clarification or add additional context in comments.

Comments

1

Just try by changing find with filter, find is to get just one object, and filter is to get an array of objects

getReportDetails(name : string) : Observable<IReport[]>
  {
    return this.getReports().pipe(
      map((reports : IReport[]) => reports.filter(p => p.reportName === name))
    );
  }

Comments

1

Even better solution for filtering returned data will be filter operator of rxjs

https://www.learnrxjs.io/operators/filtering/filter.html And then you can just easily pipe it to your older observable and return observable of filtered data which you can subscribe on

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.