【问题标题】:Angular2 return data from validation service after Http callHttp调用后Angular2从验证服务返回数据
【发布时间】:2016-07-13 19:33:44
【问题描述】:

我已经为我的注册表单构建了一个验证服务,其中一种静态方法是通过调用我的 API 来检查输入的电子邮件是否可用:

static emailAvailable(control){

    let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
    let http = injector.get(Http);
    let valid = "E-mail is available";

    http.post('https://secretapi.com/email', JSON.stringify({ email: control.value }))
    .map((res: Response) => res.json())
    .subscribe(function(result){ 
        if(result.success){
            valid = result.success; //The console.log on the line below is correct, the one at the bottom of the script never changes.
            console.log(valid);
            return null; //Doesn't do anything?
        }else{
            valid = result.error; //The console.log on the line below is correct, the one at the bottom of the script never changes.
            console.log(valid);
            return { 'invalidEmailAddress': true }; //Doesn't do anything, just like the return above
        }
    });

    console.log(valid); //Output always "E-mail is available"
}

当电子邮件可用时,它应该向表单验证器返回“null”。底部的最后一个 console.log 应该输出它在订阅调用中收到的消息。这不会发生,我不知道为什么。由于某种原因,订阅调用中发生的所有事情都包含在其中,并且永远不会到达验证器。我应该改变什么?我不知道,现在已经在网上搜索了几个小时。

【问题讨论】:

    标签: forms validation http angular subscribe


    【解决方案1】:

    您必须从验证器返回ObservablePromise

    return http.post('https://secretapi.com/email', ...
    

    console.log(...) 在这里没有任何意义,因为它将在 Observable 被创建为对象之后执行,而不是在 ajax 调用之后执行。

    如果你想在收到响应后输出一些东西,你必须把它移到subscribe

    【讨论】:

      【解决方案2】:

      所以最后这个website 得到了正确的答案。同样重要的是要注意 Angular2 表单验证器将异步验证器放在第三 (3) 参数中,而不是放在第二 (2) 参数中的数组中。我花了大约 3 个小时才弄清楚。

      函数 checkEmail(control: Control){

      let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
      let http = injector.get(Http);
      
      return new Observable((obs: any) => {
          control
              .valueChanges
              .debounceTime(400)
              .flatMap(value => http.post('https://secretapi.com/email', JSON.stringify({ email: control.value })))
              .map((res: Response) => res.json())
              .subscribe(
                  data => {
                      if(data.success){
                          obs.next(null);
                          obs.complete();
                      } else {
                          obs.next({ 'invalidEmailAddress': true });
                          obs.complete();
                      }   
                  }
              );
      });
      

      }

      验证器应该看起来像这样,第一个验证器检查 required 以及它是否实际上是一个电子邮件地址,最后一个对服务器进行异步调用以查看它是否尚未使用:

      this.registerForm = this.formBuilder.group({
              'email': ['', [Validators.required, ValidationService.emailValidator], ValidationService.emailAvailable],
          });
      

      【讨论】:

        猜你喜欢
        • 2016-11-04
        • 2018-03-08
        • 1970-01-01
        • 1970-01-01
        • 2018-03-06
        • 2019-10-23
        • 2017-08-03
        • 1970-01-01
        相关资源
        最近更新 更多