Matt
Matt

Reputation: 375

Use async pipe to show Observable data retrieved from the Application State

I have code that gets data from the Application State and then show data inside component.html.

component.ts

myData$: Observable<IMyData>;

ngOnInit() {
   this.myData$ = this.myStore.select(fetchMyData);

   // here I get a code and I use it to dispatch a new action
   this.myStore.select(codeSelector).pipe(
      map((code) => this.myStore.dispatch(myDataAction({ code: code })))
    ).subscribe();
}

component.html

{{myData$.myField}}

The code above works perfectly.

Now, instead of calling the subscribe() method inside component.ts, I'd like to use async pipe inside component.html, this way:

<ng-container *ngIf="myData$ | async as data">
{{data.myField}}
   

When I do this nothing is shown inside component.html. I understood that inside my latter code I have problems with the operators I used.

I used the async pipe many times, but only when dispatching standard actions; I never used it when the action was dispatched inside an operator.

Can you helping me understanding my error?

Upvotes: 0

Views: 2031

Answers (1)

Chellappan வ
Chellappan வ

Reputation: 27293

Try tap operator for side effects intead of map

   data$ = this.myStore.select(codeSelector).pipe(
      tap((code) => this.myStore.dispatch(myDataAction({ code: code })))
    )

Then inside component

<ng-container *ngIf="myData$ | async as data">
</ng-container>

Upvotes: 1

Related Questions