Search code examples
typescriptangularloopback

How can I to confirm the execution of all observables in a cycle - (Angular 2)?


In Angular 2, how can I confirm when "n" number of "observables" have finished:

  ...
  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);
      }
      );
  }
  ...

Thank you!


Solution

  • It should be something like this:

    //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);
      }      
      );