Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async pipe does not work in a very simple Angular app [duplicate]

First of all I have an example on Stackblitz https://stackblitz.com/edit/angular-th31vj where you can check my app.

It is a really simple app, where I have a service (StoreService) to manage data in RxJS way and 2 components: AppComponent and Catalog Component. AppComponent contains a list of categories and router-outlet. I also want to display current category under the list of categories.

Thats how my AppComponent looks like

<h3>Categories</h3>
<ul>
  <li *ngFor="let category of store.categories$ | async">
    <a [routerLink]="['/catalog', category.id]">{{ category.name }}</a>
  </li>
</ul>
<p> Selected category: {{ store.selectedCategory$.name | async }} </p>
<router-outlet></router-outlet>
import { Component, OnInit } from '@angular/core';

import { StoreService } from './store.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
  name = 'Angular';

  constructor(public store: StoreService) {}

  ngOnInit() {
    this.store.selectedCategory$.subscribe(category => console.log('App component received new category', category));
  }
}

For some reason selectedCategory$ is not displayed on the page, however I can see it in the console. I'll be glad for any help with it. Thanks.

like image 726
Andrei Belokopytov Avatar asked Mar 19 '26 06:03

Andrei Belokopytov


1 Answers

You need to apply the async pipe to the observable and then get the name from it:

{{ (store.selectedCategory$ | async).name }}

Updated StackBlitz: https://stackblitz.com/edit/angular-av1pbn

like image 107
Ingo Bürk Avatar answered Mar 20 '26 19:03

Ingo Bürk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!