了解Angular 2 observables同步

时间:2017-01-06 12:13:18

标签: javascript angular ionic2 observable

我有注册表格,应在提交前进行验证。为此我有方法,它将错误推送到错误数组。如果错误长度为零,我将此表单发送到服务器,否则我会显示错误列表。

 signUpForm() {
    this.validateOnSubmit();
    console.log(this.TAG + 'submit method fired! ');

    console.log('errors array' + JSON.stringify(this.errors));

    if (this.errors.length == 0) {

      /* Sending process*/
    } else {
      this.showOnSubmitError(this.errors);
    }
  }

表单的地址部分通过Observables向Google api请求进行验证。

 validateOnSubmit() {

    let fullAddress = this.regModel.Addresses[0].State + ', ';
    fullAddress += this.regModel.Addresses[0].Street + ', ';
    fullAddress += this.regModel.Addresses[0].City + ', ';
    fullAddress += this.regModel.Addresses[0].Zip + ' ';

    this.signUpHelperProvider.resolveAddr(fullAddress)
      .subscribe(response => {
          this.geoCodeResp = response;
          console.log(this.TAG + 'Before submission: check received geocode response stringify: ' + JSON.stringify(this.geoCodeResp));
          if (this.geoCodeResp.status != 'OK' || this.geoCodeResp.results[0].address_components.length == 1) {
            console.log('WE HAVE A PROBLEM');
            this.errors.push('Please, check if your address correct');
            console.log('WE HAVE A PROBLEM error:' + this.errors.toString());

          } else {
            this.regModel.Addresses[0].Longitude = this.geoCodeResp.results[0].geometry.location.lng;
            this.regModel.Addresses[0].Latitude = this.geoCodeResp.results[0].geometry.location.lat;
          }
        });
//
//other checks
//
console.log('total errors in method: ' + this.errors.toString());
}

这就是问题:在验证方法完成之前,实际检查错误长度。

I: [INFO:CONSOLE(9)] "SignUpHelperProvider: resolveAddr: address passed NY, Hfjdir6rhc, Durfjfu, 35682 ", source: 
I: [INFO:CONSOLE(14)] "total errors in method: ",
I: [INFO:CONSOLE(13)] "SignUpPage: submit method fired! ",
I: [INFO:CONSOLE(13)] "errors array[]", 
I: [INFO:CONSOLE(14)] "SignUpPage: Before submission: check received geocode response stringify: {"results":[{"address_components":[{"long_name":"United States","short_name":"US","types":["country","political"]}],"formatted_address":"United States","geometry":{"bounds":{"northeast":{"lat":71.5388001,"lng":-66.885417},"southwest":{"lat":18.7763,"lng":170.5957}},"location":{"lat":37.09024,"lng":-95.712891},"location_type":"APPROXIMATE","viewport":{"northeast":{"lat":49.38,"lng":-66.94},"southwest":{"lat":25.82,"lng":-124.39}}},"partial_match":true,"place_id":"ChIJCzYy5IS16lQRQrfeQ5K5Oxw","types":["country","political"]}],"status":"OK"}", 
I: [INFO:CONSOLE(14)] "WE HAVE A PROBLEM",
I: [INFO:CONSOLE(14)] "WE HAVE A PROBLEM error:Please, check if your address correct", 

有没有办法同步这个过程?我是Angular 2和Ionic 2的新手,非常感谢任何提示或帮助。

1 个答案:

答案 0 :(得分:1)

您的signUpHelperProvider.resolveAddr是异步的。您所要做的就是在订阅上执行发送过程。一种方法是使用map代替validateOnSubmit内的订阅并返回observable。 像这样 -

validateOnSubmit() {

    let fullAddress = this.regModel.Addresses[0].State + ', ';
    fullAddress += this.regModel.Addresses[0].Street + ', ';
    fullAddress += this.regModel.Addresses[0].City + ', ';
    fullAddress += this.regModel.Addresses[0].Zip + ' ';

    //return async op to subscribe
        return this.signUpHelperProvider.resolveAddr(fullAddress)
          .map(response => {
              this.geoCodeResp = response;
              console.log(this.TAG + 'Before submission: check received geocode response stringify: ' + JSON.stringify(this.geoCodeResp));
              if (this.geoCodeResp.status != 'OK' || this.geoCodeResp.results[0].address_components.length == 1) {
                console.log('WE HAVE A PROBLEM');
                this.errors.push('Please, check if your address correct');
                console.log('WE HAVE A PROBLEM error:' + this.errors.toString());

              } else {
                this.regModel.Addresses[0].Longitude = this.geoCodeResp.results[0].geometry.location.lng;
                this.regModel.Addresses[0].Latitude = this.geoCodeResp.results[0].geometry.location.lat;
              }
           //
          //other checks
           //
        console.log('total errors in method: ' + this.errors.toString());
       return response;//return the response in case required at subscription
            });

    }

您的signUpForm将是:

 signUpForm() {
    this.validateOnSubmit().subscribe(response=>{
    console.log(this.TAG + 'submit method fired! ');

    console.log('errors array' + JSON.stringify(this.errors));

    if (this.errors.length == 0) {

      /* Sending process*/
    } else {
      this.showOnSubmitError(this.errors);
    }
  });
  }

IMO您需要在提供商中执行此类异步调用