Let's take a look at this example. I'm trying to return an observable value from subscribe, but somehow I get empty value. This is scratch of my problem:
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);
});
});
template:
<div *ngFor="let values of array|async">
{{ values.id }}
{{ values.domainName }} //empty
</div>
Can anyone help with this please? Am I doing it in right way?
You should use map()
instead of subscribe()
.
subscribe
binds a handler and returns a subscription
object that you can use later to unsubscribe()
.
domainName: this.userService.getDomain(user.id).map(
(domain) => {
console.log(domain.name); // I can see this in console
return domain.name;
}
)
Also, you do not need to return an Observable
, mapping returns an observable.