John John - 26 days ago 10
TypeScript Question

Angular 2 - Observable update the returned value

How can you update the returned value so it will show when it completes?

It is being called from the html like this:

// the item.username is from a higher loop which works.
<div *ngFor="let eqItem of getTest(item.username)">



getTest(username: string): Item[] {
let itemArray: Item[];
this.usersService.subscribeItemsForUsername(username).subscribe(z => {
itemArray = z;
//return z;
});
return itemArray;
}


Here is the service:

subscribeItemsForUsername(username: string): Observable<Item[]> {
let returnedList = this.af.database.list('users', {
query: {
orderByChild: 'username',
equalTo: username,
}
});

return returnedList;
}

Answer

By using the async pipe

Ref: https://angular.io/docs/ts/latest/guide/pipes.html#async-pipe

change view to :

<div *ngFor="let eqItem of getTest(item.username) | async">

and the getTest method should return an observable like:

getTest(username: string): Observable<Item[]> {
    return this.usersService.subscribeItemsForUsername(username).map(res=> res.json());
}