Angular 角度2-可观察更新返回值

Angular 角度2-可观察更新返回值,angular,typescript,observable,subscription,angularfire2,Angular,Typescript,Observable,Subscription,Angularfire2,如何更新返回值,使其在完成时显示 它是从html调用的,如下所示: // 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.subscribeItemsForUsern

如何更新返回值,使其在完成时显示

它是从html调用的,如下所示:

// 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;
}
//item.username来自一个更高的循环,可以工作。
getTest(用户名:字符串):项[]{
let itemArray:Item[];
this.usersService.subscribeItemsForUsername(用户名).subscribe(z=>{
itemArray=z;
//返回z;
});
返回项数组;
}
服务内容如下:

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

    return returnedList;
  }
subscribeItemsForUsername(用户名:字符串):可观察{
让returnedList=this.af.database.list('users'{
查询:{
orderByChild:'用户名',
equalTo:用户名,
}
});
返回列表;
}

使用异步管道

参考:

将视图更改为:

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

通过使用异步管道

参考:

将视图更改为:

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

作为参数发送给subscribe方法的函数是一个回调函数,将来将调用它。它可能在
getTest
方法完成其工作后调用,因此您的回调将执行:
itemArray=z
,但此时不存在
itemArray

这就是为什么视图中的行
相当于
(如果subscribe方法中的回调将在
getTest
方法完成后执行)

解决方案:

正如@echonax所提到的,
Async
将是最好的解决方案

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

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

getTest(用户名:字符串):可观察{
返回此.usersService.subscribeItemsForUsername(用户名);
}

简言之:异步管道将订阅和取消订阅(在组件应被销毁之后),并将返回到阵列的
ngFor
(在本例中).

作为参数发送给subscribe方法的函数是一个回调函数,将来将调用它。它可能在
getTest
方法完成其工作后调用,因此回调函数将执行:
itemArray=z
但是
itemArray
此时不存在

这就是为什么视图中的行
相当于
(如果subscribe方法中的回调将在
getTest
方法完成后执行)

解决方案:

正如@echonax所提到的,
Async
将是最好的解决方案

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

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

getTest(用户名:字符串):可观察{
返回此.usersService.subscribeItemsForUsername(用户名);
}

简言之:异步管道将订阅和取消订阅(在组件应被销毁之后),并将返回到阵列的
ngFor
(在本例中).

有没有一种方法可以同时使用两个管道,因为我已经在使用一个pipe@John当然,只要把它放在async之后,比如
。|async | anotherPipe
有没有一种方法可以同时使用两个管道,因为我已经在使用一个pipe@John当然,只要把它放在async后面,比如
。|async | anotherPipe
有没有一种方法可以像我一样同时使用两个管道我已经在使用一个管道是的,但是额外的管道应该得到一个数组(这是异步管道将从
getTest(item.username)返回的)
observes有一种方法可以一次使用两个管道,因为我已经在使用管道是的,但是额外的管道应该得到一个数组(这是异步管道将从
getTest返回的)(项目.用户名)
可观察