[英]Throw an error "inside" an observable in angular
我想要與 ReplaySubject.next() 相同的行為,但對於錯誤 (ReplaySubject.nextError())
會使訂閱的錯誤部分執行的東西
我知道ThrowError
運算符,但它對我不起作用,因為它正在創建一個會拋出錯誤的新可觀察對象,而我希望現有可觀察對象( ReplaySubject
)在訂閱時拋出錯誤。
obs = ReplaySubject(1);
obs.nextError('some error');
obs.subscribe(res=> {'this should not execute')} err=>{console.log('this should execute')})
.error(someError)
觀察者有 3 個功能。 next
、 error
和complete
主題(和 ReplaySubjects)既是觀察者又是可觀察對象,因此您可以在主題上調用.error
。
const a$ - new Subject();
a$.subscribe({
error: err => console.log("This is an error:", err);
});
a$.error("Imperatively emitted error");
只需在switchMap
中使用throwError
。
of('some value')
.pipe(
switchMap((ms) => {
return throwError(() => new Error(`Errory McErrorFace`));
})
)
.subscribe({
next: console.log, // not called
error: console.error, // called
});
你可以在里面扔
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');
},
});
(我已經糾正了一些事情,比如不使用新的,使用不推薦使用的方法來訂閱)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.