I want the same behavior as ReplaySubject.next(), but for errors (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.
obs = ReplaySubject(1);
obs.nextError('some error');
obs.subscribe(res=> {'this should not execute')} err=>{console.log('this should execute')})
CodePudding user response:
Just throw use throwError
in a switchMap
.
of('some value')
.pipe(
switchMap((ms) => {
return throwError(() => new Error(`Errory McErrorFace`));
})
)
.subscribe({
next: console.log, // not called
error: console.error, // called
});
CodePudding user response:
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');
},
});
( I have corrected a few things, like not using new, using the deprecated method to subscribe )
CodePudding user response:
You can use .error(someError)
Observers have 3 functions. next
, error
, and complete
Subjects (and ReplaySubjects) are both observers and observables, as such you can call .error
on a subject.
const a$ - new Subject();
a$.subscribe({
error: err => console.log("This is an error:", err);
});
a$.error("Imperatively emitted error");