订阅成功功能完成时是否有任何调用功能

时间:2017-06-13 12:51:38

标签: angular angular-ui-router rxjs observable

在下面的代码中,我想在所有订阅功能成功完成时导航但在我的情况下,它是在创建客户时导航并且不等待地址创建成功。任何帮助都会得到高度赞赏

createCustomer(model: any) {
        let isSuccess:boolean=true;
        this.loading = true;
        this.errorMsg = "";
        this.createCustomerService.createCustomer(model).subscribe(res => {
          this.tempCustomer = res;
          console.log("Returned Response is");
          console.log(this.tempCustomer);
          if (model.addressType.home.street_address) {
            this.createCustomerService.addAddress(this.tempCustomer.id, "HOME", model.addressType.home, model.cc).subscribe(res => {
            },
              err => {      
                this.errorMsg = err;
                this.alertService.error(err);
                this.loading = false;
              });
          }
          if (model.addressType.work.street_address) {
            this.createCustomerService.addAddress(this.tempCustomer.id, "WORK", model.addressType.work, model.cc).subscribe(res => {
            },
              err => {
                this.errorMsg = err;
                this.alertService.error(err);
                this.loading = false;
              });
          }
          if (model.addressType.other.street_address) {
            this.createCustomerService.addAddress(this.tempCustomer.id, "OTHER", model.addressType.other, model.cc).subscribe(res => {
            },
              err => {
                this.errorMsg = err;
                this.alertService.error(err);
                this.loading = false;
              });
          }

        },
          err => {
            this.errorMsg = err;
            this.alertService.error(err);
            this.loading = false;
          },
          ()=>this.router.navigate(['/pages/searchcustomer']));

        // if (!this.errorMsg) {
        //   this.router.navigate(['/pages/searchcustomer']);
        // }
      }
    }

1 个答案:

答案 0 :(得分:1)

你可以使用forkJoin

forkJoin订阅将在所有Observable完成后调用

ob1 = this.createCustomerService.addAddress(this.tempCustomer.id, "HOME", model.addressType.home, model.cc);
ob2 =  this.createCustomerService.addAddress(this.tempCustomer.id, "WORK", model.addressType.work, model.cc)
ob3 = this.createCustomerService.addAddress(this.tempCustomer.id, "OTHER", model.addressType.other, model.cc)

    Observable.forkJoin([ob1, ob2,ob3]).subscribe(results => {
      // results[0] is our ob1
      // results[1] is our ob2
      // results[2] is our ob3
    });

注意我假设这些是Observable一次性调用,否则你可以使用 Zip