【问题标题】:How can I to confirm the execution of all observables in a cycle - (Angular 2)?如何确认一个循环中所有可观察对象的执行 - (Angular 2)?
【发布时间】:2016-08-08 02:04:25
【问题描述】:

在 Angular 2 中,我如何确认“n”个“observables”何时完成:

  ...
  for (var i = 1; i <= this.quantity; i++) {
    description = this.prefix.trim() + ' ' + i.toString();
    point = new PointModel(description, 'A', this.locationModel.id);
    this.point.create(<PointModel>point)
      .subscribe(
      pointModel => {
        Materialize.toast('Se ha guardado el punto \"' + pointModel.description + '\"', 2000);
      },
      error => {
        Materialize.toast('Se ha generado un error: \"' + error + '\"', 2000);
      }
      );
  }
  ...

谢谢!

【问题讨论】:

    标签: typescript angular loopback


    【解决方案1】:

    应该是这样的:

    //create and fill points array
    var points:PointModel[] = [];
    for (var i = 1; i <= this.quantity; i++) {
      description = this.prefix.trim() + ' ' + i.toString();
      points.push(new PointModel(description, 'A', this.locationModel.id));
    }
    
    Observable.from(points).flatMap(point=>{this.point.create(<PointModel>point)})
    .subscribe(
      pointModel => {
        Materialize.toast('Se ha guardado el punto \"' + pointModel.description + '\"', 2000);
      },
      error => {
        Materialize.toast('Se ha generado un error: \"' + error + '\"', 2000);
      },
      () => {
         Materialize.toast('All points have been created!', 2000);
      }      
      );
    

    【讨论】:

      【解决方案2】:

      我的最终代码是:

        for (var i = 1; i <= this.quantity; i++) {
          description = this.prefix.trim() + ' ' + i.toString();
          points.push(new PointModel(description, 'A', this.locationModel.id));
        }
      
        Observable.fromArray(points).flatMap( //'fromArray' is deprecated, instead use 'from'
          point => {
            return this.point.create(<PointModel>point); //the return was the key here...
          }
        )
          .subscribe(
          pointModel => {
            Materialize.toast('Se ha guardado el punto \"' + pointModel.description + '\"', 2000);
          },
          error => {
            Materialize.toast('Se ha generado un error: \"' + error + '\"', 2000);
          },
          () => {
            this.loadPointsFromModelId(this.pointModel.id);
          }
          );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-18
        • 2017-05-17
        • 1970-01-01
        • 2020-06-03
        • 1970-01-01
        • 2019-04-23
        • 2017-06-07
        • 1970-01-01
        相关资源
        最近更新 更多