[英]How to invoke exception for Subject Observer in map?
我有這個 0bserver 主題:
public subject = new Subject<any>();
我推送這樣的消息:
this.subject.next({value : 1});
然后我嘗試執行以下操作:
this.subject.map(data => {
if (!data || !data.value) {
throw new Error('No value, no function...');
} else {
return data;
}
}).subscribe((data: IFilterCustom) => {
// WORK HERE WITH FILLED DATA
}, err => {
console.error('Error');
});
我嘗試檢查傳入的數據是否不包含我調用異常的value
。 怎么做?
在最新的 rxjs 中,您可以使用管道執行此操作:
import { map, catchError } from 'rxjs/operators'
import { of } from 'rxjs'
this.subject.pipe(
map((data) => {
if (!data || !data.value) {
throw new Error('No value, no function...');
} else {
return data;
}
}),
catchError(() => {
console.log('Error')
return of(null) // Be sure to return an observable here! The 'of' function creates an observable out of the argument
})
)
一旦在 observable 中拋出錯誤,就會調用catchError
部分。 這對於捕獲請求中的任何網絡錯誤也很有用。
如果您不需要錯誤處理並且您只需要主題不發出值,那么您可以使用過濾器
import { filter } from 'rxjs/operators'
this.subject.pipe(
filter((data) => {
return (data && data.value)
})
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.