I'm struggling to get my head around observables in Angular2. I have a 2 subscriptions to an observable within an observeable forEach.
So it's as follows:
- forEach gets the route ID (poll id)
- (Nested in 1) subscribe gets the poll from the database using the route ID (poll id)
- (Nested in 2) subscribe gets the createdBy user from the database using the poll ids createdById
As you can see there's a lot of nesting going on which just doesn't feel right. Is there a better way for me to achieve this?
This is my code:
poll: Poll;
createdBy: string;
constructor(public route: ActivatedRoute, public teamPollsService: TeamPollsService) { }
ngOnInit(): void {
let id: any;
// 1.
this.route.params.forEach((params: Params) => {
id = params['id'];
// 2.
this.pollService.getPoll(id).subscribe((x) => {
this.poll = x;
// 3.
this.users.getDbUser(x.createdById).subscribe((user) => {
createdBy = `${user.firstName} ${user.lastName}`;
});
});
});
Thanks.
Use
flatMap()
instead:It will automatically unwrap nested observables and will help to avoid problem similar to callback hell.