我试图在服务中调用一个函数,但我一直有 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/