This is my Angular component code
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import { reauthenticateWithCredential, User, UserCredential } from '@angular/fire/auth';
import { EmailAuthProvider } from '@angular/fire/auth';
import { getAuth } from '@angular/fire/auth';
@Component({
selector: 'app-update-password',
templateUrl: './update-password.component.html',
styleUrls: ['./update-password.component.css']
})
export class UpdatePasswordComponent {
constructor() { }
updatePassword = new FormGroup({
currentPassword: new FormControl(null, [Validators.required, Validators.minLength(6)]),
newPassword: new FormControl(null, [Validators.required, Validators.minLength(6)]),
confirmNewPassword: new FormControl(null, [Validators.required, Validators.minLength(6)]),
});
updateAccountPassword(): void {
console.log('updatePassword:', this.updatePassword.value)
const auth = getAuth()
const user = auth.currentUser;
const credential = EmailAuthProvider.credential(
auth.currentUser?.email!,
this.updatePassword.value.currentPassword!
)
reauthenticateWithCredential(user, credential).then(() => {
// User re-authenticated.
}).catch((error) => {
// An error ocurred
// ...
});
}
}
I'm getting the following typescript error(see the screenshot) from -
I can understand it's asking user
parameter type should be of firebase User
type, but it's getting type null
for that.
New to typescript world. Need some help to fix this.
CodePudding user response:
auth.currentUser
can be null
if no user is logged in. You can use a type guard that'll also ensure that this code runs only if a user is logged in as shown below:
updateAccountPassword(): void {
const auth = getAuth()
const user = auth.currentUser;
// ...
if (user) {
reauthenticateWithCredential(user, credential).then(() => {
// User re-authenticated.
})
} else {
console.log("No user logged in")
}
}