我创建了authService,在其中创建了一个检查电子邮件是否已经注册的函数。在进行员工验证时,我将此函数称为forbiddenEmails,但出现错误:无法读取newZoneAwarePromise中定义的authService的属性

这是我的代码:

import { Component, OnInit } from '@angular/core';
import { NgForm, FormGroup, FormControl, Validators } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/Rx';

import { AuthService } from '../auth/auth.service';

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
  genders = ['male', 'female'];
  departments = ['IT', 'Account', 'HR', 'Sales'];
  employeeForm: FormGroup;
  employerData = {};

  constructor(private authService: AuthService) { }

  ngOnInit() {
    this.employeeForm = new FormGroup({
      'name': new FormControl(null, [Validators.required]),
      'email': new FormControl(
          null,
          [Validators.required, Validators.email],
          this.forbiddenEmails
      ),
      'password': new FormControl(null, [Validators.required]),
      'gender': new FormControl('male'),
      'department': new FormControl(null, [Validators.required])
    });
  }

  registerEmployee(form: NgForm) {
    console.log(form);
    this.employerData = {
      name: form.value.name,
      email: form.value.email,
      password: form.value.password,
      gender: form.value.gender,
      department: form.value.department
    };

    this.authService
        .registerEmployee(this.employerData)
        .then(
            result => {
              console.log(result);
              if (result.employee_registered === true) {
                console.log('successful');
                this.employeeForm.reset();
                // this.router.navigate(['/employee_listing']);
              }else {
                console.log('failed');
              }
            }
        )
        .catch(error => console.log(error));
  }

  forbiddenEmails(control: FormControl): Promise<any> | Observable<any> {
    const promise = new Promise<any>((resolve, reject) => {
      this.authService
          .employeeAlreadyRegistered(control.value)
          .then(
              result => {
                console.log(result);
                if (result.email_registered === true) {
                  resolve(null);
                }else {
                  resolve({'emailIsForbidden': true});
                }
              }
          )
          .catch(error => console.log(error));
      /*setTimeout(() => {
        if (control.value === '[email protected]') {
          resolve({'emailIsForbidden': true});
        } else {
          resolve(null);
        }
      }, 1500);*/
    });
    return promise;
  }

}


AuthService代码:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/Rx';

@Injectable()
export class AuthService {
    url = 'http://mnc.localhost.com/api/user/';
    response: object;

    constructor(private http: Http) {}

    signInUser(email: string, password: string): Promise<any>  {
        console.log('1111');
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this.http
            .post(this.url + 'signIn', { email: email, password: password }, options)
            .toPromise()
            .then(this.extractData)
            .catch(this.handleError);
    }

    registerEmployee(employeeData: object): Promise<any> {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this.http
            .post(this.url + 'registerEmployee', employeeData, options)
            .toPromise()
            .then(this.extractData)
            .catch(this.handleError);
    }

    employeeAlreadyRegistered(email: string): Promise<any> {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this.http
            .post(this.url + 'employeeAlreadyRegistered', { email: email }, options)
            .toPromise()
            .then(this.extractData)
            .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body || {};
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }

}


registerEmployee函数也使用authservice,但是在添加此验证之前它运行良好,所以这意味着forbiddenEmails函数存在一些问题。

我是angular js的新手,无法解决问题。

最佳答案

ngOnInit()中,更改声明电子邮件自定义验证器的方式:

ngOnInit() {
  this.employeeForm = new FormGroup({
    'name': new FormControl(null, [Validators.required]),
    'email': new FormControl(
        null,
        [Validators.required, Validators.email],
        (control: FormControl) => {
            // validation email goes here
            // return this.forbiddenEmails(control);
        }
    ),
    'password': new FormControl(null, [Validators.required]),
    'gender': new FormControl('male'),
    'department': new FormControl(null, [Validators.required])
  });
}


验证程序导致您出错,因为this的上下文在您分配它时就更改为FormGroup类:

'email': new FormControl(
    null,
    [Validators.required, Validators.email],
    (control: FormControl) => this.forbiddenEmails
)


这就是为什么在调用undefined时收到authService错误的原因,因为它是在FormGroup类中找到的,而不是在Component

注意:仅当用户尝试提交表单或对电子邮件元素失去关注时,才检查forbiddenEmails。将其放入验证器中并不好,因为验证器往往会执行多次。

希望能有所帮助

10-02 12:09