1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Initialize BehaviorSubject with value from Observable

Discussão em 'Angular' iniciado por Sergej Bjakow, Outubro 15, 2024 às 08:23.

  1. I was trying to create an item counter for Wishlist Entries in my header area and tried to apply the solutions suggested here (for Cart Items) Change shopping-cart count in header in Angular

    Unfortunately this does not quite cut it for me since the solutions are ignoring that there might be initial Data served as an Observable. In my case I'm storing the WishlistObjects with StorageMap (@ngx-pwa/local-storage), and that data is only returned as an Observable and I'm not quite sure how to associate that initial Data with the BehaviorSubject in the Service that is supposed to keep track of modifications. That's why I came up with this idea of having two seperate observables, that I combine...

    COMPONENT:
    export class WishlistLinkComponent{

    merged$: Observable<number> = combineLatest([this.wishListService.getWishList(),this.wishListService.getCartCount()]).pipe(
    map(([wishlist, count]) => {
    console.log('wishlist: ',wishlist);
    console.log('count: ',count);
    return count ?? (wishlist.entries?.length ?? 0);
    })
    )

    constructor(protected wishListService: WishListService) {}

    }


    SERVICE:
    export class EmvAnonymousWishListService {
    constructor(
    private storage: StorageMap,
    private productService: ProductService
    ) { }

    private cartSubj:BehaviorSubject<number | undefined> = new BehaviorSubject<number| undefined>(undefined);


    getCartCount(): Observable<number> {
    return this.cartSubj.asObservable();
    }

    getWishList(): Observable<Cart> {
    return this.storage.get('wishlist')
    .pipe(
    switchMap((productCodes: string[]) => this.productService.getProducts(productCodes)),
    );
    }

    addEntry(productCode: string): void {
    this.this.storage.get('wishlist').subscribe(productCodes => {
    productCodes.push(productCode);
    this.cartSubj.next(productCodes.length)
    //store Logic...
    });
    }

    removeEntry(productCode: string): void {
    this.this.storage.get('wishlist').subscribe(productCodes => {
    const filteredProductCodes = productCodes.filter((code: string) => {
    return code !== productCode;
    });
    this.cartSubj.next(productCodes.length)
    //store Logic...
    });
    }

    }


    I know this is ugly, but I don't know how to handle a scenario like this, with only one observable covering everything.

    Continue reading...

Compartilhe esta Página