1

我创建了 authService,在其中创建了一个检查电子邮件是否已注册的函数。虽然员工验证我将此函数称为禁止电子邮件,但它给出了一个错误:无法读取在 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 === 'test@test.com') {
          resolve({'emailIsForbidden': true});
        } else {
          resolve(null);
        }
      }, 1500);*/
    });
    return promise;
  }

}

验证服务代码:

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,但在我添加此验证之前它运行良好,这意味着禁止电子邮件函数存在一些问题。

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

4

1 回答 1

2

在您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在用户尝试提交表单或失去对电子邮件元素的关注时检查。将其放入验证器并不好,因为验证器往往会执行多次。

希望有帮助

于 2017-09-03T07:30:09.977 回答