I have an angular 2 service
import * as localforage from "localforage";
import { ReplaySubject } from 'rxjs/ReplaySubject';
@Injectable()
export class CommentService {
private localForage = require("localforage");
addComment (myvalue: string): Observable<Comment[]> {
var reply:ReplaySubject<any> = new ReplaySubject(1);
localforage.setItem(that.key, that.elencoCommenti).then(function (value) {
//throw new Error("Value cannot be 3");
reply.throw(Error('Error2'));
// reply.next( value );
// reply.complete();
});
return reply;
}
}
This service cointains a method for raise an exception. When i try to subscribe
submitComment(){
// Variable to hold a reference of addComment
let commentOperation:Observable<string>;
commentOperation = this.commentService.addComment(this.model)
// Subscribe to observable
commentOperation.subscribe(
comments => {
console.log('ok:');
console.log(comments);
},
err => {
// Log errors if any
console.log('error:');
console.log(err);
});
}
i don't receive the error. How raise exception in ReplaySubject?
ReplaySubject is a variant of a Subject which keeps a cache of previous values emitted by a source observable and sends them to all new observers immediately on subscription. This behavior of replaying a sequence of old values to new subscribes is where the name for this type of a subject comes from.
The ReplaySubject is comparable to the BehaviorSubject in the way that it can send “old” values to new subscribers. It however has the extra characteristic that it can record a part of the observable execution and therefore store multiple old values and “replay” them to new subscribers.
Use a ReplaySubject when you need more than the last given value. (For example, the previous five values) Or you want to set a time window for the values can be validly sent to subscribers. Use an AsyncSubject when you only want the last value to be passed to the subscribers.
When a new subscriber subscribes to the ReplaySubject instance, it will synchronously emit all values in its buffer in a First-In-First-Out (FIFO) manner. The ReplaySubject will also complete, if it has observed completion; and it will error if it has observed an error.
reply.error("some error");
should do it.
However I would not suggest you to throw an error in a ReplaySubject
- as any error will finalize the Subject
and make it unusable for any future use and will automatically unsubscribe any subscribers - unless that is what you want to achieve here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With