简体   繁体   中英

Multiple Observable subscription

I need to subscribe multiple times in order to get the right data fro my NoSQL database. In order to fetch user list of specific project, I do this:

ngOnInit() {
    //Subscription 1 (Service): Get project data
    this.projectService.getCurrentproject().take(1).subscribe(projectData => {
        console.log('Got project data.');
        //Subscription 2: Get project user IDS
        this.af.database.list('/project_roles/'+projectData.$key)
            .subscribe((userMeta) => {
                });
            });
}
  • As you can see, a subscription, inside a subscription, inside a subscription.. And each subscription depends on the previous one reslt.

  • Subscription 3 and 4 can be parallel.

The code works well, but am I missing something or this is how I suppose working with multiple subscription that the result of the previous one depends the next?

Update : There seem a problem with Subscription #2. The subscription is not yet complete but I start iterating over the list, which give me a double user list!

Try this.

ngOnInit() {
    this.projectService.getCurrentproject().take(1)
        .flatMap(projectData => {
            return this.af.database.list('/project_roles/'+projectData.$key)
        })
        .flatMap(userMeta => {
            let subs = userMeta.map(projectRole => {
                return Observable.zip([
                    this.af.database.object('/roles/'+projectRole.$value),
                    this.af.database.object('/users/'+projectRole.$key)
                ]).map(([roleData, user]) => {
                    user.role = roleData.$value;
                    return Observable.of(user)
                })
            });
            return Observable.zip(subs)
        })
        .subscribe(users => {
            this.users = users
        })
}

Basically I am composing the subscriptions to get a single observable which emits the users array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM