Search code examples
spartacus-storefront

how to get Product Code from current product service


I'm new to spratacus, i want to get product code in type script. product$: Observable = this.currentProductService.getProduct(); how to get product code? please help.


Solution

  • Your question could be rephrased to more specific: How to get the value from the RxJs stream of data in Angular?

    Answer:

    It depends, where you want to access the value:

    a) Most likely: you want to get it in the HTML template of your component. Then use Angular's async pipe:

    <ng-container *ngIf="product$ | async as product">
      <!-- use `product` variable here -->
    </ng-container>
    

    b) Or in your Typescript class (of component or service). Then you can subscribe to the observable to get the value. That said, it's not recommended approach, because then you need to manually dispose subscriptions to avoid memory leaks!

    ngOnInit() {
      this.sub = this.product$.subscribe(product => {
        // use `product` variable here
      })
    }
    
    /*...*/
    
    ngOnDestroy() {
      this.sub?.unsubscribe();
    }
    

    Referecnces