[英]Multiple Observable subscription
I need to subscribe multiple times in order to get the right data fro my NoSQL database. 我需要多次订阅才能从NoSQL数据库中获取正确的数据。 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. 订阅3和4可以是并行的。
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. 更新 :订阅#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 基本上我正在编写订阅以获取发出users数组的单个observable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.