【问题标题】:angualr2 return observable from subscribeangualr2 从订阅返回 observable
【发布时间】:2017-05-23 15:04:27
【问题描述】:

让我们看一下这个例子。我正在尝试返回一个可观察的值 从订阅,但不知何故我得到空值。 这是我的问题的划痕:

this.userService.getAll().subscribe((userCollection) => {

        userCollection.data.forEach((user) => {

            let data = {
                id: user.id
                domainName: this.userService.getDomain(user.id).subscribe(
                    (domain) => {
                        console.log(domain.name); // I can see this in console
                        return Observable.of(domain.name);
                    }
                )
            };

            this.array.push(data);
        });
 });

模板:
<div *ngFor="let values of array|async"> {{ values.id }} {{ values.domainName }} //empty </div>

有人可以帮忙吗?我做得对吗?

【问题讨论】:

    标签: angular observable angular-promise angular2-services


    【解决方案1】:

    您应该使用map() 而不是subscribe()

    subscribe 绑定一个处理程序并返回一个subscription 对象,您可以稍后将其用于unsubscribe()

    domainName: this.userService.getDomain(user.id).map(
                    (domain) => {
                        console.log(domain.name); // I can see this in console
                        return domain.name;
                    }
                )
    

    另外,您不需要返回 Observable,映射返回一个 observable。

    【讨论】:

      猜你喜欢
      • 2017-02-17
      • 2019-03-09
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多