this.pickupStatus.emit is not a function

Viewed 1137

I have a provider that listens to changes to my firestore database and changes the status of a driver pickup request status. here is my pickuprequest function in my driver's provider

 getDriverPickupRequest(id)
{
this.DriverCollection.doc<Driver>(id).valueChanges()
                .subscribe(data => {
                        this.pickuprequest.changePickupStatus(data.pickupRequest);

} 

Now i have a service that watches the change and emits it to my home page.

private pickupRequest = new BehaviorSubject<boolean>(false);
public pickupStatus = this.pickupRequest.asObservable();

changePickupStatus(value: boolean) {
this.pickupStatus.emit(value);
}

constructor(public http: HttpClient) {
//console.log('Hello PickuprequestProvider Provider');

}

Now i get an error that says 'this.pickupStatus.emit is not a function'. What is wrong with the code?

3 Answers

.emit() only works on EventEmitter, using .next() on pickup status won't work as Observable is read-only.

A BehaviorSubject has a next method on it that is used to push new values to the observable.

Problem: You're calling emit on pickupStatus which is an Observable when you should have called next on pickupRequest which is a BehaviorSubject

Fix:

private pickupRequest = new BehaviorSubject<boolean>(false);
public pickupStatus = this.pickupRequest.asObservable();

changePickupStatus(value: boolean) {
  this.pickupRequest.next(value);
}

Use this.pickupRequest.next(value); where we are essentially pushing a new value on the pickupRequest which is a BehaviorSubject by using the next method on it.

emit method exist on EventEmitter object not on BehaviourSubject. Over here you are exposing the stream using this.pickupRequest.asObservable() method. I believe this is safest way to expose a stream so that the consumer of this stream will not push any data into a stream. Basically to prevent leaky abstraction. If consumer tries to do pickupStatus.next(data) on that it will result to an error. This is expected behavior. This way we give readonly access to consumer of a stream.

In order to send data over a stream you have to call .next method on BehaviorSubject instance, it auto magically let subscribers knows that new data has pushed into a stream.

pickupRequest.next(data)
Related