Admiral
Admiral

Reputation: 1908

Get value of Observable<SomeObject> in an object

In Angular I have an interface defined of a category. Because the categories have a nested structure (by defining a parent) I defined the following interface in category.ts:

Now, how can I get the value of the subCategories parameter in the template?

the interface

import { Observable } from 'rxjs';

export interface Category{
    name: string,
    displayName: string,
    displayIndex: number;
    subCategories?: Observable<Category[]>;
    parent?: string;
}

the compontent

...imports...

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.less']
})
export class HomeComponent implements OnInit {

  categories: Category[];

  constructor(private categoriesService: CategoriesService) { }

  ngOnInit() {

    this.categoriesService.all().subscribe((cats) => {
      this.categories = cats;
      console.log(cats[0].subCategories); // outputs: Observable {_isScalar: false, source: Observable, operator: MapOperator} => If I subscribe to it and console that, it outputs the desired values.
    });
  }

}

the template


<div class="row">
    <div class="col-xs-12" *ngFor="let cat of categories; let i = index">

        <div class="row">
            <div class="col-xs-12">
                <p><a [routerLink]="['categories', cat?.name]">{{ cat?.display_name }}</a></p>
            </div>
        </div>

        <div class="row">
            <div class="col-xs-12" *ngFor="let sub of categories.subCategories | async; let j = index">
                {{ sub.name }}
            </div>
        </div>
    </div>
</div>

It shows only the queried top-level categories.

Upvotes: 1

Views: 847

Answers (1)

Austin Fahsl
Austin Fahsl

Reputation: 378

In the template, use the async pipe after category.subCategories to ensure that the latest value emitted from subCategories is used:

{{category.subCategories | async}}

Docs: https://angular.io/api/common/AsyncPipe

Edit:

It looks like in your second ngFor, you mean to do cat.subCategories | async instead of categories.subCategories | async. That will ensure all subCategories of each category get displayed.

Upvotes: 1

Related Questions