TypeScript报错ts(2339):Promise类型上不存在uid、updateProfile属性如何解决
报错根因
AngularFireAuth的currentUser属性本身是Promise<User>类型,而非直接的用户实例对象- 你直接对Promise对象调用只有
User实例才具备的uid属性、updateProfile方法,不符合TypeScript的类型校验规则,因此触发2339错误
修复方案
推荐直接从createUserWithEmailAndPassword的回调结果中获取刚注册的用户实例,不需要额外调用currentUser,修改后的代码如下:
export class SignupPage implements OnInit { email: string; pwd: string; username: string; constructor(public fs: AngularFirestore, public af: AngularFireAuth, public nav: NavController) { } signup() { this.af.createUserWithEmailAndPassword(this.email, this.pwd).then((userCredential) => { // 直接从返回的用户凭证中取user实例 const user = userCredential.user; localStorage.setItem('usesrid', user.uid); user.updateProfile({ displayName: this.username, photoURL: '' }).then(() => { this.nav.navigateRoot('/tabs') }).catch(err => { alert(err.message) }) }).catch(err => { alert(err.message) }) } }
如果你确实需要使用currentUser,需要先等待Promise执行完成拿到实例,可采用async/await写法优化:
async signup() { try { await this.af.createUserWithEmailAndPassword(this.email, this.pwd); // 等待currentUser的Promise resolve拿到用户实例 const user = await this.af.currentUser; localStorage.setItem('usesrid', user.uid); await user.updateProfile({ displayName: this.username, photoURL: '' }); this.nav.navigateRoot('/tabs'); } catch (err) { alert(err.message); } }
内容的提问来源于stack exchange,提问作者Favour R.
相关产品推荐
相关产品推荐

