简体   繁体   English

如何在地图中为主题观察者调用异常?

[英]How to invoke exception for Subject Observer in map?

I have this 0bserver subject:我有这个 0bserver 主题:

public subject = new Subject<any>();

I push message like this:我推送这样的消息:

this.subject.next({value : 1});

Then I try to do the following:然后我尝试执行以下操作:

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');
});

I try to check if incoming data not contains value I invoke exception.我尝试检查传入的数据是否不包含我调用异常的value How to do that?怎么做?

In the latest rxjs you do this using pipes:在最新的 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
  })
)

The catchError part will be called once an error has been thrown in the observable.一旦在 observable 中抛出错误,就会调用catchError部分。 This is also useful to catch any network errors in requests.这对于捕获请求中的任何网络错误也很有用。

If you don't need error handing and you just need the subject not to emit values, then you can use filter如果您不需要错误处理并且您只需要主题不发出值,那么您可以使用过滤器

import { filter } from 'rxjs/operators'

this.subject.pipe(
  filter((data) => {
    return (data && data.value)
  })
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM