Angular 6 ,'Cannot read property of undefined' 在服务中调用函数时

标签 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。

最佳答案

由于验证器将从另一个上下文调用,因此 authenticationService 在那里不可用。尝试使用箭头函数,以便保留 this 上下文:

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

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

关于Angular 6 ,'Cannot read property of undefined' 在服务中调用函数时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53956174/

相关文章:

php - IONIC 4 和 PHP 当构建 apk 时不起作用

javascript - 带有 Spring Boot 的 Thymeleaf 或 Angular 4

javascript - 如何在 angularjs 2 中嵌套子路由

typescript - 如何使用 jest 测试 Apollo Server 订阅?

typescript - 如何在 TypeScript 中定义泛型数组?

node.js - Yelp 融合 : Cannot get Tokens

c# - 发布base64转换后的图像数据

javascript - 如何在不相关的组件之间共享数据? Angular 6

javascript - 创建对象/函数的实例将 JavaScript 转换为 TypeScript

python - 使用 azure blob 存储向 API 发出 http post 请求