Angular 2 / Angular 4 - Cannot read property of authService of defined at newZoneAwarePromise

208 views Asked by At

I have created authService in which I have created a function which checks whether email is already registered. While employee validation I call this function forbiddenEmails but it gives an error: Cannot read property of authService of defined at newZoneAwarePromise

Here is my code:

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 Code:

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);
    }

}

The registerEmployee function also uses authservice but it worked fine before I added this validation, so that mean there is some problem in forbiddenEmails function.

I am new to angular js and not able to resolve the issue.

1

There are 1 answers

0
masterpreenz On BEST ANSWER

In your ngOnInit() change the way you declare the custom validator for emails:

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])
  });
}

the validator was causing you the error because the context of this changed to the FormGroup class the moment you assign it:

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

that is why you are getting an undefined error when calling authService because it was looking on FormGroup class not in your Component

NOTE: Only check the forbiddenEmails when user tries to submit the form OR loses focus on the email element. Putting it inside a validator is not good as validators tend to be executed many times.

hope that helps