3

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?

3
  • 3
    dwsubscriptions is not an Observable / async. It seems like you want to do *ngFor="let dwsubscription of dwsubscriptions" and then {{ (dwsubscription | async).params.data Commented Nov 7, 2018 at 17:25
  • A better question is why do you have an array of Observables vs. getting an array of data from one Observable? Commented Nov 7, 2018 at 17:30
  • I would suggest you to use forkJoin from the component itself Commented Nov 7, 2018 at 17:45

3 Answers 3

0

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

0

Try using joinFork

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

);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.