【问题标题】:Angular 2 async validatorAngular 2 异步验证器
【发布时间】:2019-03-12 10:50:19
【问题描述】:
   isUnameTaken(formCtrl:FormControl): Promise<any>|Observable<any>{
    var status ;
    console.log(this.formGroup);

    this.http.post("http://localhost:3000/user/isAvaliable", { userName: formCtrl.value}).subscribe((resp:any)=>{
      console.log(resp);
       status = resp.status;
      console.log(status);
      if (status === 'success') {
        return Promise.resolve({ userExists: true });
      } else {
        return Promise.resolve(null);
      }
    });


  }

我的状态为未定义,因为发布请求需要时间来解决我试图解决使用 Promise.resolve 来返回承诺 那么如何以适当的方式等待响应

上面的函数是角度验证器函数

【问题讨论】:

  • 使用 rxjs map 函数代替 subscribe。如果是 rxjs 6,则需要结合使用 mappipe
  • 请问我现在的问题是我想等待该状态并基于此我想返回验证结果。添加地图和管道将如何解决这个问题,请原谅我的无知
  • 因为管道允许我们转换Observable 发出的值。这样,调用者可以subscribe 到 Observable,并等待它发出它的值
  • 有没有这样的例子
  • 你使用的是哪个版本的 RXJS?

标签: angular


【解决方案1】:

您可以使用Observables map 函数来转换Observable 发出的值,如下所示:

import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

// ...

return this.http.post("http://localhost:3000/user/isAvaliable", { userName: formCtrl.value }).pipe(
  map((resp: any) => {
    console.log(resp);
    status = resp.status;
    console.log(status);
    return status === 'success' ? { userExists: true } : null;
  })
);

【讨论】:

  • 感谢您的帮助,但如果我使用的是以前的 http 模块,可以做同样的事情吗?它是否使用了管道和地图?
  • 是的,你可以直接使用.map而不是.pipe.map一起使用
猜你喜欢
  • 2017-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-01
相关资源
最近更新 更多