Код:
// Angular Modules
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Title } from '@angular/platform-browser';
// Services
import { AuthService } from '../../services/auth.service';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.less']
})
export class ProfileComponent implements OnInit {
title = 'Profile';
showError = false;
showSuccess = false;
showAccountRemovalModal = false;
profileForm: FormGroup;
passwordForm: FormGroup;
removeAccountForm: FormGroup;
user: Object;
userEmail: String;
errorMessage: String;
successMessage: String;
constructor(private TitleService: Title,
private fb: FormBuilder,
private authService: AuthService) {
// Creates the profileForm schema with validations.
this.profileForm = this.fb.group({
name: [{value: null, disabled: false}, Validators.required],
username: [{value: null, disabled: true}, Validators.required],
email: [{value: null, disabled: false}, [Validators.required, Validators.email]]
});
// Creates the passwordForm schema with validations.
this.passwordForm = this.fb.group({
passwords: fb.group({
password: [null, [Validators.required]],
confirmPassword: [null, [Validators.required]]
}, {validator: this.passwordMatchValidator})
});
// Creates the removeAccountForm schema with validations.
this.removeAccountForm = this.fb.group({
emailAddress: fb.group({
verifyEmail: [null, [Validators.required]]
}, {validator: this.emailMatchValidator})
});
}
// Compares the password and confirmPassword fields for a match.
passwordMatchValidator(form: FormGroup) {
return form.controls['password'].value === form.controls['confirmPassword'].value ? null : {
'mismatch': true
};
}
// Compares the entered email address field for account removal.
emailMatchValidator(form: FormGroup) {
return form.controls['verifyEmail'].value === this.userEmail ? null : {
'mismatch': true
};
}
// Updates the profile of the User.
updateProfile(id, name, email) {
const user = {
name: name,
email: email,
};
this.authService.updateUser(id, user).subscribe(data => {
if (data) {
console.info(data);
this.successMessage = 'Your profile information has been updated!';
this.showSuccess = true;
} else {
this.errorMessage = data.msg;
this.showError = true;
}
});
}
removeUser(id) {
this.authService.removeUser(id);
}
ngOnInit() {
// Gets the current User object.
this.authService.getUser().subscribe(profile => {
this.user = profile;
this.userEmail = profile.email;
},
err => {
console.info(err);
return false;
});
// Sets the page title.
this.TitleService.setTitle('WODGate - ' + this.title);
}
}
Внизу, в моем ngOnInit, я нажимаю строку на userEmail, которая действительна. console.info(profile.email) возвращает допустимую строку. Ошибка, которую я получаю, связана с функцией emailMatchValidator, в которой я пытаюсь прочитать this.userEmail. На самом деле, даже если я попытаюсь прочитать this.user где-нибудь в моем .ts-файле, я получаю ту же ошибку. В моем HTML я должен прочитать значения с помощью оператора ?, такого как user?.email, чтобы он заработал.
Мне нужно иметь возможность читать this.userEmail в моем файле .ts, но я получаю сообщение об ошибке «Невозможно прочитать свойство userEmail из undefined».
Вот функция из моего сервиса для справки:
// Return Single User
getUser() {
const headers = new Headers();
this.loadToken();
headers.append('Authorization', this.authToken);
headers.append('Content-Type', 'application/json');
return this.http.get('http://localhost:4000/api/users/' + this.user.id, {headers: headers})
.map(res => res.json());
}





Функция emailMatchValidator потеряла свой контекст - это означает, что this сейчас не отображается компоненту. Вам нужно явно привязать контекст или использовать arrow function.
Использование явной привязки
{ validator: this.emailMatchValidator.bind(this) })
вы говорите, что this покажет заданное значение функции bind - в нашем случае ProfileComponent.
Прекрасно работает. Спасибо!