角度6,在服务中调用函数时,“无法读取未定义的属性”

时间:2018-12-28 09:20:47

标签: angular typescript http-post angular-services angular-httpclient

我正在尝试在服务内部调用函数,但是我一直在使用Cannot read property 'authenticationService' of undefined

我已经在组件的构造函数中初始化authenticationService

组件:

 export class RegisterComponent implements OnInit {
  error: string;
  isLinear = true;
  registerFormGroup: FormGroup;
  loading = false;
  form: FormGroup;
  studentRegister: any;
  samePassword = false;
  hide = true;
  hide1 = true;
  matcher = new MyErrorStateMatcher();

constructor(
   private router: Router,
   private _formBuilder: FormBuilder,
   private http: HttpClient,
   private i18nService: I18nService,
   private authenticationService: AuthenticationService
) {
}

ngOnInit() {
    this.registerFormGroup = this._formBuilder.group({
    first_name: [null, Validators.compose([Validators.required,                 Validators.minLength(3), Validators.maxLength(20)])],
    last_name: [null, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(20)])],
    email: [null, Validators.compose([Validators.required, Validators.email])],
    password: [null, Validators.compose([Validators.required])],
    tel: [null, Validators.compose([Validators.required])],
    confirmPassword: [null]
}, {
  validator: [this.checkPasswords, this.checkEmailUnique]
});
}

checkEmailUnique(group: FormGroup) {
 const mail = group.controls.email.value;
 const obj: any = {'email': mail, } ;
 this.authenticationService.checkEmailUnique(obj);
}

checkPasswords(group: FormGroup) { // here we have the 'passwords' group
 const pass = group.controls.password.value;
 const confirmPass = group.controls.confirmPassword.value;
 return pass === confirmPass ? null : {notSame: true};
}}

register() {
   console.log('the form is', this.registerFormGroup);
     // stop here if form is invalid
     if (this.registerFormGroup.invalid) {
      return;
     }
    this.loading = true;
    this.authenticationService.register(this.registerFormGroup.value)
     .pipe(finalize(() => {
        this.loading = false;
       }))
       .subscribe(credentials => {
        log.debug(`${credentials.email} successfully logged in`);
        this.router.navigate(['/'], {replaceUrl: true});
       }, error => {
        log.debug(`Login error: ${error}`);
        this.error = error;
       });
   }

服务:

@Injectable()
 export class AuthenticationService {
  private _credentials: Credentials | null;

  constructor(private http: HttpClient) {
    const savedCredentials = sessionStorage.getItem(credentialsKey) ||    localStorage.getItem(credentialsKey);
     if (savedCredentials) {
     this._credentials = JSON.parse(savedCredentials);
     }
     }

register(context: UserInfo): Observable<Credentials> {
    // Replace by proper authentication call
    let data = {
     email: context.email,
     token: '',
     user_type: ''
     };

    return this.http.post('/account/create_new/', JSON.stringify({
     first_name: context.first_name,
     last_name: context.last_name,
     email: context.email,
     password: context.password,
     tel: context.tel,
     user_type: 'S',
     student: {}
    }), httpOptions)
     .pipe(
       map((response: any) => {
        console.log(response.user_type);
        data.user_type = response.user_type;
        data.token = response.token;
        this.setCredentials(data, true);
         return data;
        })
      );
}

checkEmailUnique(obj: any) {
     return this.http.post('/check_email/', obj, httpOptions)
     .pipe(
      map((response: any) => {
      console.log(response);
      return response;
    })
  );}}

authenticationService中调用register()可以正常工作。 checkEmailUnique应该向后端发送POST请求,以检查电子邮件是否已经存在,并返回true或false。

1 个答案:

答案 0 :(得分:1)

由于将从另一个上下文中调用验证器,所以那里没有authenticationService。尝试使用箭头功能,以便保留此上下文:

checkEmailUnique = (group: FormGroup) => {
 const mail = group.controls.email.value;
 const obj: any = {'email': mail, } ;
 this.authenticationService.checkEmailUnique(obj);
}

此外,由于您来自authenticationService的checkEmailUnique函数将返回Observable,因此您将需要使用asyncValidators。