javascript - Angular 2/Angular 4 - 无法读取在 newZoneAwarePromise 处定义的 authService 的属性

标签 javascript angular angular-promise angular-observable

我创建了 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 === '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 但在我添加此验证之前它工作正常,这意味着 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
)

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

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

希望对你有帮助

关于javascript - Angular 2/Angular 4 - 无法读取在 newZoneAwarePromise 处定义的 authService 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46020993/

相关文章:

javascript - 通过单击标签来切换下拉菜单

angularjs - JS Promises - 使这个 promise 嵌套更有效的方法?

javascript - Angular Material Grid 列表延迟加载

javascript - React props : Should I pass the object or its properties? 有多大区别?

angular - Angular2中通过路由名称获取路由组件

javascript - Angular 无法找到名称缓冲区

angular - Angular 路由参数 Observable 的 Observable.forkJoin

javascript - 简化 Javascript 中的 promise

javascript - 使用 Promise Angularjs 工厂进行异步调用

javascript - 如何将输入元素及其标签包装到一个 div 中并将其放在其父元素之后?