角度 2 return 可从订阅中观察到

angualr2 return observable from subscribe

我们来看看这个例子。我正在尝试 return 一个可观察的值 来自订阅,但不知何故我得到了空值。 这是我的问题的开始:

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>

有人可以帮忙吗?我的做法对吗?

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

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

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

此外,您不需要 return 一个 Observable,映射 return 一个 observable。