Avij
Avij

Reputation: 694

How to use observable subject variable in component?

I have a shared service with providers in my root component. I an using this service to manipulate parent for the count of items selected. On the parent this count is surrounded by anchor so it takes user to all items selected. However i am using a variable of shared service to do this, while i believe there should be some way so that i can call observable to fetch the info. My code for service is

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Promo } from './model';

@Injectable()
export class CheckoutEventService {
    private checkOutSucess = new Subject<boolean>();
    //private checkOutFailureMsg = new Subject<string>();
    private checkedOutPromo = new Subject<Promo>();
    //I could not find to remove this and use above property somehow.
    public bogusPromoObject :Promo;

    checkOutPromo$ = this.checkedOutPromo.asObservable();
    checkOutSucess$ = this.checkOutSucess.asObservable();

    checkOutPromoSvc(promo: Promo) {
        this.checkedOutPromo.next(promo);
        this.bogusPromoObject=promo;
    }
    checkOutPromoSucessSvc(msg: boolean) {
        this.checkOutSucess.next(msg);
    }
    }

I am now using "bogusPromoObj" to render this behaviour. However i am keen to know if there is a way to reuse the observable to get the history. Just so its clear i am already subscribing to promo observable in parent, however there is a routing involved in next step where i want to fetch history of every item selected.

Upvotes: 1

Views: 1696

Answers (1)

Estus Flask
Estus Flask

Reputation: 222344

A couple of checkOutPromo$ observable and checkOutPromoValue value is the usual recipe in a situation like this.

If a subject is allowed to have initial value that will be changed later, BehaviorSubject can be used:

private checkedOutPromo = new BehaviorSubject<Promo|null>(null);

Its subscribers will receive current value synchronously. If it's initial, then null will be received. Since this subject has current value, it can be retrieved with checkedOutPromo.value, this makes checkOutPromoValue unnecessary. The value won't be available through asObservable, so the subject should become public instead of checkOutPromo$. This imposes encapsulation problem; for instance, checkOutPromo.unsubscribe() is available for all subscribers but can be harmful.

If bogusPromoObject is used only in view, it can be omitted in favour of async pipe:

{{ checkoutEventService.checkOutPromo$ | async }}

Upvotes: 1

Related Questions