【问题标题】:Processing result from multiple observables to database and adding to database once将多个可观察的结果处理到数据库并添加到数据库一次
【发布时间】: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


【解决方案1】:

您可以使用forkJoin 来简化实现。

此外,您可以使用mergeMapupdate 调用返回的承诺组合到可观察流中。

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/operator/mergeMap';

Observable.forkJoin(
  this.getData(this.id),
  this.getAnotherData(this.id)
)
.mergeMap(([data, anotherData]) => {
  this.data = data;
  this.data.another = anotherData;
  return firebase
    .database()
    .ref('/test/' + this.channel.id)
    .update(this.data);
})
.subscribe(undefined, this.onError);

【讨论】:

  • 非常感谢! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-28
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多