我想從 API 回應中進行管道和過濾,但回應格式如下。
JSON:
{ activeAwards: [ { name: 'x', status: 'valid' }, { name: 'y', status: 'valid' }, { name: 'z', status: 'invalid' } ] }
我試過點擊進入“activeAwards”并過濾它。
代碼:
.pipe(
tap(data => {
data.activeAwards.filter(award =>
award.status === 'valid';
);
})
)
.subscribe(response => {
console.log(response);
}),
catchError(error => {
return error;
});
但是根據上面的代碼我得到了所有的3個物件,也就是全部,應該是2個物件
uj5u.com熱心網友回復:
tap 不會更改流資料,而 filter 不會更改輸入陣列。而是使用 map 并分配過濾結果。
.pipe(
map(data => {
return {
...data,
activeAwards: data.activeAwards.filter(award => award.status === 'valid');
};
}),
).subscribe(response => {
console.log(response);
}),
catchError(error => {
return error;
});
uj5u.com熱心網友回復:
在這種情況下,您想要訪問map過濾后的陣列,因為您正在更改需要傳遞給訂閱的資料:
.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需要在其回呼中回傳一些東西。您可以回傳EMPTY(從 匯入rxJs)以使流永遠不會到達訂閱塊,或者您可以回傳of(null)并在訂閱中添加空值處理。
.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
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/535100.html
