I want to pipe and filter from an API response, but response format is as follows.
JSON:
{ activeAwards: [ { name: 'x', status: 'valid' }, { name: 'y', status: 'valid' }, { name: 'z', status: 'invalid' } ] }
I have tried tap to get in 'activeAwards' and filter it.
Code:
.pipe(
tap(data => {
data.activeAwards.filter(award =>
award.status === 'valid';
);
})
)
.subscribe(response => {
console.log(response);
}),
catchError(error => {
return error;
});
But according to the code above I`m getting all 3 objects, which is all of them, it should be 2 objects
CodePudding user response:
tap doesn't change streamed data and filter doesn't change the input array. Instead use map and assign the filter result.
.pipe(
map(data => {
return {
...data,
activeAwards: data.activeAwards.filter(award => award.status === 'valid');
};
}),
).subscribe(response => {
console.log(response);
}),
catchError(error => {
return error;
});
CodePudding user response:
In this case, you want to map
to the filtered array since you're changing the data that needs to fall through to the subscribe:
.pipe(
// catch the error before transforming the stream to prevent runtime errors
catchError(() => {...})
map((data) => {
data.activeAwards = data.activeAwards.filter(...);
return data;
})
).subscribe(() => {
//handle the data
});
catchError
needs to return something in its callback. You can either return EMPTY
(imported from rxJs
) to cause the stream to never hit the subscribe block, or you can return of(null)
and add handling in your subscribe for a null value.
.pipe(
catchError(err => {
return of(null)
// or return EMPTY - the subscribe block will not run in this case.
})
).subscribe(res => {
if(res) {
//handle the result
}
})