1

In this Plunker I have this template :

 <span *ngFor="let a of Articles">{{a}}</span>

This is the component class :

export class App
{
    Articles: number[];
    constructor()
    {
        this.getData();
    }
    simualteDb()
    {
        return new Promise((a, b) =>
        {
            setTimeout(function()
            {
                a(
                {    // notice , an object ,not an array
                    data: [0, 1, 2]
                });
            }, 500)
        });
    }
    async getData()
    {
        this.Articles = (await this.simualteDb()).data;
    }
}

This does work and I do see 012 in the output. But I want to use the async pipe.

So I want my template to be :

 <span *ngFor="let a of Articles |async ">{{a}}</span>

But there is a problem.

Articles is not an array. It is an object with data prop which is the required array.

I can't do something like this :

   <span *ngFor="let a of Articles.data |async ">{{a}}</span>

I've created another plunker which returns only an array :

and It does work with |async.

Question:

Looking at my first code , How can I use the async pipe while still resolving an object and not an array ?

{data: [0, 1, 2]} 
developer033
  • 24,267
  • 8
  • 82
  • 108
Royi Namir
  • 144,742
  • 138
  • 468
  • 792

1 Answers1

2

Giving you the other option to use the async pipe (which you mentioned you wanted), means that you need to have an Observable to work with... service returns Observable:

getArticles() {
  return this.http.get('url')
    .map(res => res.json())
}

And in the component assign the Observable:

ngOnInit() {
  this.Articles = this.service.getArticles()
}

Then you can use the async pipe in your view like so:

<div *ngFor="let a of (Articles | async)?.data">{{a}}</div>

Demo

AT82
  • 71,416
  • 24
  • 140
  • 167
  • Yeah I 've just seen this [answer](http://stackoverflow.com/a/35302622/859154) and it can be used with promises also - [here is a demo plunker of mine with promise and async pipe](https://plnkr.co/edit/mK2tWJmmkm4qlZ7DWYq4?p=preview). so the "_you need to have an Observable_" part is incorrect ;-) – Royi Namir Apr 08 '17 at 19:09
  • @Royi I also tried it like you did but with `await` infront of the Promise as your plunker included it. I was trying to figure out what was wrong :D – eko Apr 08 '17 at 19:12
  • 1
    Yes, it can be used with promises but AsyncPipe can't consume array or object. Only `Observable, Promise or EventEmitter` The next wont work `{data: [0, 1, 2]} | async` and `[0,1,2] | async` – yurzui Apr 08 '17 at 19:15
  • @yurzui Thanks for the clarification. – Royi Namir Apr 08 '17 at 19:16