简体   繁体   English

在 angular 中的可观察对象“内部”抛出一个错误

[英]Throw an error "inside" an observable in angular

I want the same behavior as ReplaySubject.next(), but for errors (ReplaySubject.nextError())我想要与 ReplaySubject.next() 相同的行为,但对于错误 (ReplaySubject.nextError())

Something that will make the error part of the subscription execute会使订阅的错误部分执行的东西

I know about the ThrowError operator, but it doesn't work for me because it is creating a new observable that will throw an error, while I want an existing observable ( ReplaySubject ) to throw an error upon subscription.我知道ThrowError运算符,但它对我不起作用,因为它正在创建一个会抛出错误的新可观察对象,而我希望现有可观察对象( ReplaySubject )在订阅时抛出错误。

obs = ReplaySubject(1);
obs.nextError('some error');
obs.subscribe(res=> {'this should not execute')} err=>{console.log('this should execute')})

You can use .error(someError)你可以使用.error(someError)

Observers have 3 functions.观察者有 3 个功能。 next , error , and complete nexterrorcomplete

Subjects (and ReplaySubjects) are both observers and observables, as such you can call .error on a subject.主题(和 ReplaySubjects)既是观察者又是可观察对象,因此您可以在主题上调用.error

const a$ - new Subject();
a$.subscribe({
  error: err => console.log("This is an error:", err);
});
a$.error("Imperatively emitted error");

Just throw use throwError in a switchMap .只需在switchMap中使用throwError

of('some value')
  .pipe(
    switchMap((ms) => {
      return throwError(() => new Error(`Errory McErrorFace`));
    })
  )
  .subscribe({
    next: console.log, // not called
    error: console.error, // called
  });

You can throw, inside of it你可以在里面扔

import { ReplaySubject, tap } from 'rxjs';

const obs = new ReplaySubject(1);

obs.next('hello');

const obsConsumer = obs.pipe(
  tap(() => {
    throw 'err';
  })
);

obsConsumer.subscribe({
  next: (res) => {
    console.log('this should not execute');
  },
  error: (err) => {
    console.log('this should execute');
  },
});

Stackblitz堆栈闪电战

( I have corrected a few things, like not using new, using the deprecated method to subscribe ) (我已经纠正了一些事情,比如不使用新的,使用不推荐使用的方法来订阅)

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

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