【发布时间】:2018-01-02 11:54:12
【问题描述】:
我需要使用 getData() 和 getAnotherData() 处理我通过 observable 获得的 2 个不同的 API 数据结果,并将结果保存到数据库中。 我不喜欢在处理两个可观察数据时必须检查的方式。你有什么不同的做法吗?
import { Observable } from 'rxjs/Rx';
class dataClass {
data: any;
id: string;
constructor (id) {
this.id = id;
this.proccess()
}
proccess() {
let i = 0;
this.getData(this.id).subscribe(
res => {
this.data = {
// process API data
}
},
undefined,
() => this.onLoad(++i)
);
this.getAnotherData(this.id).subscribe(
res => {
this.data.another = {
// process API data
}
},
undefined,
() => this.onLoad(++i)
);
}
getData(id):Observable<any> {
// return JSON API obserable
}
getAnotherData(id):Observable<any> {
// return JSON API obserable
}
onLoad(i) {
if (i == 2) {
// send processed data back to db
firebase.database()
.ref('/test/' + this.channel.id)
.update(this.data, this.onError);
}
return;
}
onError(error) {
if (error) {
console.error('Error: ' + error);
} else {
console.log("Data saved successfully.");
}
}
}
var adm = new dataClass("id");
【问题讨论】:
-
两个 observable 的数据处理方式是否相同?
-
@0mpurdy 不,这就是我必须拆分它们的原因。
-
对不起,我完全误读了这个问题(这里已经很晚了)你可以使用 merge 并在合并的 observable 完成时执行
onLoad(我认为你只是忽略了合并的流)@ 987654322@ 尝试拖动弹珠(包括完整的),看看会发生什么。你问的是这个吗?我最好在发布答案之前检查一下,以防我再次出错!
标签: javascript typescript asynchronous rxjs observable