我正在嘗試注冊用戶,然后updateUserProfile使用如此命名的函式。
首先,我遇到了type用戶的問題,我通過User從 firebase匯入型別解決了這個問題,并檢查是否有currentUser, 以滿足null可能性。
我認為問題出在最后一次檢查上,因為函式的內容沒有運行。即我認為用戶尚未注冊。
注意:如果我這樣做: const user: User = this.auth.currentUser;
我遇到了updateProfile(user)這個錯誤type 'User | null' is not assignable to type 'User'.
如果我做: const user: User | null = this.auth.currentUser;
我收到此錯誤:
Argument of type 'User | null' is not assignable to parameter of type 'User'.
這就是為什么我最終像這樣檢查:
if (this.auth.currentUser) {
const user: User = this.auth.currentUser;
那么我怎樣才能做到這一點呢?
一個選項可能是onAuthStateChanged在注冊home后簽入螢屏然后運行updateUserProfile,我將在其中傳遞名稱,我將在注冊時將其保存在 redux 中。
在火力地堡-V8我可能updateUserProfile只是createUserWithEmailAndPassword功能。我相信在 v9 中也應該有一種方法可以做到這一點,但也應該Typescript如此。
任何幫助,將不勝感激。
謝謝
import { createUserWithEmailAndPassword, getAuth, sendPasswordResetEmail, updateProfile, User } from 'firebase/auth';
async signUp(email: string, password: string, name: string) {
createUserWithEmailAndPassword(this.auth, email, password)
.then(async userCredential => {
console.log('userCredential', userCredential);
await this.updateUserProfile(name);
}).catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
})
}
async updateUserProfile(name: string) {
if (this.auth.currentUser) {
const user: User = this.auth.currentUser;
updateProfile((user), {
displayName: name, photoURL: `https://gravatar.com/avatar${md5(user.email)}?d=identicon`
}).then((user) => {
// Profile updated!
console.log('Profile updated!', user);
}).catch((error) => {
// An error occurred
console.log(error);
});
}
}
uj5u.com熱心網友回復:
this.auth.currentUser如果身份驗證狀態尚未加載,則可以為 null。在這種情況下,您可以從 userCredential 本身傳遞用戶物件,如下所示:
createUserWithEmailAndPassword(this.auth, email, password)
.then(async userCredential => {
console.log('userCredential', userCredential);
await this.updateUserProfile(userCredential.user, name);
// Pass user object from here ^^^
})
// Take user object as parameter
async updateUserProfile(user: User, name: string) {
updateProfile((user), {
displayName: name, photoURL: `https://gravatar.com/avatar${md5(user.email)}?d=identicon`
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/367531.html
