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]} 
0

1 Answer 1

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

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

4 Comments

Yeah I 've just seen this answer and it can be used with promises also - here is a demo plunker of mine with promise and async pipe. so the "you need to have an Observable" part is incorrect ;-)
@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
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 Thanks for the clarification.

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.