【问题标题】:Angular - Store multiple Get request in one jsonAngular - 在一个json中存储多个Get请求
【发布时间】:2018-01-26 11:49:42
【问题描述】:

我有一个问题。我想将多个GET 请求的信息存储在一个JSON 中,我需要一些建议。我的应用中有两个调用,第一个调用为每个元素提供了一些值,如下所示:

//values: Number [] =[]; 
this._ValuesService.getValues().subscribe(
          result => {
            this.values= result;
          },
          err => console.log(err)
        );

第二个GET是这样的:

//calcs: Calcs[] = []; 
this._CalcsService.getCalcs(value)
          .subscribe(
            res => {
              this.calcs= res;
            },
            err => {
              console.log(err);
              alert('Error =C');
            }
          );

我想同时为Values[] 中的每个值调用GET CalcsService 并将其仅存储在一个JSON 中。我考虑使用ForkJoin 的选项,但我认为这不是解决这个问题的方法。有什么想法吗?

提前致谢!

【问题讨论】:

  • 两次调用将是两个结果,除非您以某种方式合并它们。但是你想要这样做的原因是什么?只需等待两者都完成,然后处理结果。感觉就像您正在尝试解决一个可能不是真正问题的问题。
  • 为什么不 ForkJoin?我认为它可以解决您的问题
  • forkJoin 不会产生 1 个单独的 JSON,而是一个包含两个单独 JSON 结果的数组。
  • 您可以在此处使用 zip 运算符了解更多信息 -> blog.angularindepth.com/…
  • 同样在 forkJoin 之后,您可以在结果上使用 map 或 reduce 从数组中生成一个 json

标签: json angular typescript get


【解决方案1】:

我希望您的意思是所有计算结果,而不是计算 + 值的混合结果。请尝试以下操作:

this._ValuesService.getValues()
  .map(values => values.map(value => this._CalcsService.getCalcs(value)) // Create an Observable foreach value
  .switchMap(obs => Observable.combineLatest(obs)) // Call the endpoint foreach value
  .subscribe(result => { // Array of results from calc
    console.log(result);
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2019-06-08
    • 2023-03-31
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多