【问题标题】:Angular 2 - Observable update the returned valueAngular 2 - Observable 更新返回值
【发布时间】:2017-03-26 14:07:28
【问题描述】:

如何更新返回的值以便在完成时显示?

它是这样从 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;
}

这里是服务:

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

    return returnedList;
  }

【问题讨论】:

    标签: angular typescript observable subscription angularfire2


    【解决方案1】:

    通过使用异步管道

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

    将视图更改为:

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

    getTest 方法应该返回一个类似的 observable:

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

    【讨论】:

    • 有没有办法一次使用 2 个管道,因为我已经在使用管道了
    • @John 当然,只要把它放在 async 之后就像 ... | async | anotherPipe
    【解决方案2】:

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

    这就是为什么视图中的&lt;div *ngFor="let eqItem of getTest(item.username)"&gt; 行等同于&lt;div *ngFor="let eqItem of []"&gt;(如果您在订阅方法中的回调将在getTest 方法完成后执行。

    解决方案:

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

    <div *ngFor="let eqItem of getTest(item.username) | async">
    
    getTest(username: string):Observable<Item[]>{
    return this.usersService.subscribeItemsForUsername(username);
    }
    

    简而言之:Async 管道将订阅和取消订阅(在组件应该被销毁之后)并将返回到 ngFor 数组(在这种情况下)。

    【讨论】:

    • 有没有办法一次使用 2 个管道,因为我已经在使用管道了
    • 是的,但是额外的管道应该得到一个数组(这就是异步管道将从getTest(item.username) Observable 返回的内容
    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 2016-10-25
    • 2016-12-18
    • 1970-01-01
    • 2018-07-08
    • 2018-04-02
    • 2016-10-18
    • 2017-06-24
    相关资源
    最近更新 更多