Austen Stone
Austen Stone

Reputation: 1069

Use ngFor with async pipe to display array of observables

I'm having a hard time understanding why ngFor isn't working with an array of observables.

export class DashboardComponent implements OnInit {
    dwsubscriptions: Observable<Dwsubscription>[] = new Array();

    ngOnInit() {
        this.dwsubscriptions.push(
            this.devicewiseService.getSubscription('Randomizer', '1', 3, 1, -1)
        )
    }
}

Then my html

<div *ngFor="let dwsubscription of dwsubscriptions | async">
    <p>value: {{dwsubscription.params.data}}</p>
</div>

getSubscriptions is returning an observable

getSubscription(device: string, variable: string, type: number, count:number, length:number): Observable<Dwsubscription> {

I am getting the error

ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

This works fine if I do async pipe on a single observable returned from getSubscription(). Why can't I push those observables to an array and then iterate through them in my template using ngFor?

Upvotes: 3

Views: 3640

Answers (3)

Daniel
Daniel

Reputation: 723

Try using joinFork

this.results = forkJoin(this.locations, this.distances).pipe(
  map(([locations, distances]) => locations.concat(distances))

);

Upvotes: 0

Pezetter
Pezetter

Reputation: 2862

Your question implies that you want an array of Observables. That means you would need to fix how you reference dwsubscriptions in your html. dwsubscriptions is not an Observable in your example. It is an array of Observables. So no need to use the async pipe on dwsubscriptions ;

Heres a quick Stackblitz example

The chaing comes from:

<ul>
  <li *ngFor="let obs of dwsubscriptions">
  {{obs | async | json}}
  </li>
</ul>

Upvotes: 0

ovidiup
ovidiup

Reputation: 31

You are creating an array of observables. You'll have to loop over each observable and then use the async pipe for each one.

Try this:

<div *ngFor="let dwsubscription of dwsubscriptions">
  <div *ngIf="dwsubscription | async as dw">
    <p>value: {{dw.params.data}}</p>
  </div>
</div>

Upvotes: 0

Related Questions