Reputation: 2620
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.
Upvotes: 3
Views: 10371
Reputation: 669
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
Upvotes: 1
Reputation: 2408
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))
);
}
Upvotes: 1
Reputation: 18113
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
Upvotes: 7