Angular 角度表单自定义验证程序http observable在http调用时返回null

Angular 角度表单自定义验证程序http observable在http调用时返回null,angular,rxjs,angular-forms,angular-observable,Angular,Rxjs,Angular Forms,Angular Observable,我正在尝试设置一个表单字段,它将检查电子邮件是否存在。我已经看了几个例子,并且验证工作正常,但是当我实现http管道时,映射到我的服务的可观察对象,它会将其作为null抛出吗?我可以假设我的服务不正确地连接到它,但我不太确定 有人能帮我吗 core.js:6014错误类型错误:无法读取未定义的属性“emailService” 应用程序组件.ts export class AppComponent implements OnInit { signUpForm: FormGroup; c

我正在尝试设置一个表单字段,它将检查电子邮件是否存在。我已经看了几个例子,并且验证工作正常,但是当我实现http管道时,映射到我的服务的可观察对象,它会将其作为null抛出吗?我可以假设我的服务不正确地连接到它,但我不太确定

有人能帮我吗

core.js:6014错误类型错误:无法读取未定义的属性“emailService”

应用程序组件.ts

export class AppComponent implements OnInit {

  signUpForm: FormGroup;

  constructor(private fb: FormBuilder, private emailService: EmailService) { }

  ngOnInit() {
    this.signUpForm = this.fb.group({
      name: ['', Validators.required],
      email: ['', [Validators.required], [this.validateEmailNotTaken]]
    });
  }

  //Validator for checking if email name is taken or not
  validateEmailNotTaken(control: AbstractControl): Observable<{ [key: string]: any } | null> {

      if (control.value === null || control.value.length === 0) {
        return of(null);
      }
      else {
        return timer(1000).pipe(
          switchMap(() => {


            this.emailService.checkEmailExists(control.value).pipe(
              map(res => {
                //Do what with response
                console.log(res);

                if (!res) {
                  return { taken: true };
                }

                return of(null);
              })
            );


          })
        );
      }


  }

}
 interface IServerCheckEmailExists {
    "available": boolean;
}
export interface ICheckEmailExists {
    taken: boolean;
}

@Injectable({ providedIn: 'root' })
export class EmailService {

    constructor(private _http: HttpClient) {
    }

    checkEmailExists(email: string): Observable<ICheckEmailExists[]> {

        var postObject = {"action": "checkEmailExists"};
        return this._http.post<IServerCheckEmailExists[]>("myapiurl/" + email, postObject).pipe(
            map(o => o.map((sp): ICheckEmailExists => ({
                taken: sp.available
            })))
        );
    }
}
导出类AppComponent实现OnInit{
报名表格:FormGroup ;;
构造函数(私有fb:FormBuilder,私有emailService:emailService){}
恩戈尼尼特(){
this.signUpForm=this.fb.group({
名称:['',验证器。必需],
电子邮件:[''[Validators.required],[this.validateemailnottake]]
});
}
//验证程序,用于检查是否使用了电子邮件名称
ValidateeMailNotTake(控件:AbstractControl):可观察{
if(control.value==null | | control.value.length==0){
返回(空);
}
否则{
返回计时器(1000)。管道(
开关映射(()=>{
this.emailService.checkEmailExists(control.value).pipe(
地图(res=>{
//如何应对
控制台日志(res);
如果(!res){
返回{take:true};
}
返回(空);
})
);
})
);
}
}
}
email.service.ts

export class AppComponent implements OnInit {

  signUpForm: FormGroup;

  constructor(private fb: FormBuilder, private emailService: EmailService) { }

  ngOnInit() {
    this.signUpForm = this.fb.group({
      name: ['', Validators.required],
      email: ['', [Validators.required], [this.validateEmailNotTaken]]
    });
  }

  //Validator for checking if email name is taken or not
  validateEmailNotTaken(control: AbstractControl): Observable<{ [key: string]: any } | null> {

      if (control.value === null || control.value.length === 0) {
        return of(null);
      }
      else {
        return timer(1000).pipe(
          switchMap(() => {


            this.emailService.checkEmailExists(control.value).pipe(
              map(res => {
                //Do what with response
                console.log(res);

                if (!res) {
                  return { taken: true };
                }

                return of(null);
              })
            );


          })
        );
      }


  }

}
 interface IServerCheckEmailExists {
    "available": boolean;
}
export interface ICheckEmailExists {
    taken: boolean;
}

@Injectable({ providedIn: 'root' })
export class EmailService {

    constructor(private _http: HttpClient) {
    }

    checkEmailExists(email: string): Observable<ICheckEmailExists[]> {

        var postObject = {"action": "checkEmailExists"};
        return this._http.post<IServerCheckEmailExists[]>("myapiurl/" + email, postObject).pipe(
            map(o => o.map((sp): ICheckEmailExists => ({
                taken: sp.available
            })))
        );
    }
}
接口IServerCheckEmailExists{
“可用”:布尔值;
}
导出接口ICheckEmailExists{
采取:布尔;
}
@可注射({providedIn:'root'})
导出类电子邮件服务{
构造函数(私有的http:HttpClient){
}
checkEmailExists(电子邮件:字符串):可观察{
var postObject={“action”:“checkEmailExists”};
返回此文件。_http.post(“myapiurl/”+电子邮件,postObject).pipe(
map(o=>o.map((sp):ICheckEmailExists=>({
拍摄:sp可用
})))
);
}
}

您的ValidateeMailNotTake方法没有获取组件的实例。您需要在创建formGroup时绑定此文件。按如下方式修改代码:-

this.signUpForm = this.fb.group({
  name: ['', Validators.required],
  email: ['', [Validators.required], [this.validateEmailNotTaken.bind(this)]]
});

请尝试此方法并让我知道。

您的ValidateeMailNotTake方法没有获取该组件的实例。您需要在创建formGroup时绑定此文件。按如下方式修改代码:-

this.signUpForm = this.fb.group({
  name: ['', Validators.required],
  email: ['', [Validators.required], [this.validateEmailNotTaken.bind(this)]]
});

请尝试此操作并让我知道。

我在您的代码中看到的唯一问题是您没有将呼叫返回到
this.emailService.checkEmailExists(control.value)
中的
开关映射
,因为您正在使用
{}
。大概是这样的:

从“@angular/core”导入{Component,OnInit};
进口{
FormGroup,
造模工,
验证器,
抽象控制
}从“@angular/forms”;
从“rxjs”导入{Observable,of,timer};
从“rxjs/operators”导入{switchMap,map};
从“/email.service”导入{EmailService};
@组成部分({
选择器:“我的应用程序”,
templateUrl:`./app.component.html`,
样式URL:[`./app.component.css`]
})
导出类AppComponent实现OnInit{
报名表格:FormGroup ;;
构造函数(私有fb:FormBuilder,私有emailService:emailService){}
恩戈尼尼特(){
this.signUpForm=this.fb.group({
名称:[“”,验证器。必需],
电子邮件:[“”,[Validators.required],[this.validateemailnottake.bind(this)]]
});
}
//验证程序,用于检查是否使用了电子邮件名称
ValidateeMailNotTake(
控件:抽象控件
):可见{
if(control.value==null | | control.value.length==0){
返回(空);
}否则{
返回计时器(1000)。管道(
开关映射(()=>{

//就在这里我在您的代码中看到的唯一问题是,您没有返回对
this.emailService.checkEmailExists(control.value)
内的
开关映射的调用,因为您正在使用
{}
。类似这样的情况:

从“@angular/core”导入{Component,OnInit};
进口{
FormGroup,
造模工,
验证器,
抽象控制
}从“@angular/forms”;
从“rxjs”导入{Observable,of,timer};
从“rxjs/operators”导入{switchMap,map};
从“/email.service”导入{EmailService};
@组成部分({
选择器:“我的应用程序”,
templateUrl:`./app.component.html`,
样式URL:[`./app.component.css`]
})
导出类AppComponent实现OnInit{
报名表格:FormGroup ;;
构造函数(私有fb:FormBuilder,私有emailService:emailService){}
恩戈尼尼特(){
this.signUpForm=this.fb.group({
名称:[“”,验证器。必需],
电子邮件:[“”,[Validators.required],[this.validateemailnottake.bind(this)]]
});
}
//验证程序,用于检查是否使用了电子邮件名称
ValidateeMailNotTake(
控件:抽象控件
):可见{
if(control.value==null | | control.value.length==0){
返回(空);
}否则{
返回计时器(1000)。管道(
开关映射(()=>{

//就在这里,您是否正确地将emailservice导入appcomponent?若要重现此问题,将需要stackblitz。是的,我将导入内容从示例代码中删除,但我已从“../\u services”导入{emailservice};
我是否正确地访问了
管道(switchMap()中的
emailservice.checkEmailExists()
?您是否正确地将emailservice导入appcomponent?若要重现此问题,将需要stackblitz。是的,我没有在示例代码中进行导入,但我从“../\u services”导入了
import{emailservice};
我是否正确地访问了
管道(switchMap()中的
emailservice.checkEmailExists()
?装订是问题所在。谢谢!装订是问题所在。谢谢!