[英]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.