Search code examples
angularngrx-store

How to assign state value into string variable in Angural Component [ngrx Store]


This is my code. But It gives error.

public productKey: string;

    constructor(private store: Store<AppState>) {
      this.productKey = store.pipe(select('product'), map((productState: ProductState) => productState.productKey));
    }

Solution

  • The Expresion:

    store.pipe(select('product'), map((productState: ProductState) => productState.productKey))
    

    return a Observable with string type (Observable). To assign value from the store to the local variable you need to subscribe it:

    store
      .pipe(select('product'), map((productState: ProductState) => productState.productKey))
      .subscribe(value => this.productKey = value);
    

    If you use it in your HTML, the better solution is to assign Observable to the variable and extract value directly inside template using Async Pipe.