I have a service that calls the API like this:
return this._http
.post(appSettings.apiUrl + 'SomeController/SomeAction', params, {withCredentials: true, headers: this.headers})
.timeoutWith(appSettings.maxTimeHttpCalls, Observable.defer(() => Observable.throw(this._feedbackService.timeout())))
.map((response: Response) => response.json().data);
Now I want to implement a filter function on that call using rxjs/add/operator/filter
, but I can't get it to work properly.
This is the approach I have taken:
return this._http
.post(appSettings.apiUrl + 'SomeController/SomeAction', params, {withCredentials: true, headers: this.headers})
.timeoutWith(appSettings.maxTimeHttpCalls, Observable.defer(() => Observable.throw(this._feedbackService.timeout())))
.filter(response => response.json().data.Type === 5)
.map((response: Response) => response.json().data);
But no matter what I filter on, the ngFor
loop produces nothing as long as the filter is in there. If I remove it, everything works as expected.
Am I supposed to add the filter before or after the map
?
Can I filter on the response JSON like that, or do I need to use another syntax?
Example JSON
Here's an example of what the response JSON looks like:
data: [
{
"Type": 5,
"Description": "Testing",
"ID": "001525"
}
]
Here another sample based on @martin's answer:
Whether
filter()
should be before or aftermap()
depends on what you want to do.I guess in your case
map()
should go beforefilter()
because you want to first decode data from JSON and then filter it. The way you have it now won't return anything if the condition infilter()
resolves tofalse
because you're using in on the entireresponse
. Maybe this is what you're going for...I don't know what your response structure is but I'd go with something like this which makes more sense:
Edit:
I'd use
concatMap()
withfrom()
to transform the array to an Observable stream:See live demo: http://plnkr.co/edit/nu7jL7YsExFJMGpL3YuS?p=preview
Jan 2019: Updated for RxJS 6