【发布时间】:2020-05-21 16:29:18
【问题描述】:
我遇到了有关身份验证和用户配置文件的问题。 我正在使用 ionic v4 / angular 和 firestore。 目前我可以通过电子邮件和密码登录,但是当我想进入个人资料以获取此用户数据时,我面对的是一个空白页面。
这里是我的 user.service.ts
import { Injectable } from '@angular/core'
import { AngularFireAuth } from '@angular/fire/auth'
import { first } from 'rxjs/operators'
import { auth } from 'firebase/app'
interface user {
username: string,
uid: string
}
@Injectable()
export class UserService {
private user: user
constructor(private afAuth: AngularFireAuth) {
}
setUser(user: user) {
this.user = user
}
getUsername(): string {
return this.user.username
}
reAuth(username: string, password: string) {
return this.afAuth.auth.currentUser.reauthenticateWithCredential(auth.EmailAuthProvider.credential(username, password))
}
updatePassword(newpassword: string) {
return this.afAuth.auth.currentUser.updatePassword(newpassword)
}
updateEmail(newemail: string) {
return this.afAuth.auth.currentUser.updateEmail(newemail)
}
async isAuthenticated() {
if(this.user) return true
const user = await this.afAuth.authState.pipe(first()).toPromise()
if(user) {
this.setUser({
username: user.email.split('@')[0],
uid: user.uid
})
return true
}
return false
}
getUID(): string {
return this.user.uid
}
}
这里是我的 login.page.ts
export class LoginPage implements OnInit {
username: string = ""
password: string = ""
constructor(public afAuth: AngularFireAuth, public user: UserService, public router: Router) { }
ngOnInit() {
}
async login() {
const { username, password } = this
try {
// kind of a hack.
const res = await this.afAuth.auth.signInWithEmailAndPassword(username, password)
if(res.user) {
this.user.setUser({
username,
uid: res.user.uid,
})
console.log(res.user.uid)
this.router.navigate(['/home-results'])
}
} catch(err) {
alert("Bad Credentials")
console.dir(err)
if(err.code === "auth/user-not-found") {
console.log("User not found")
}
}
}
}
profile.page.ts
@Component({
selector: 'app-profil',
template: `
<!-- User logged in -->
<ng-template #authenticated>
<div *ngIf="auth.user | async as user">
<h3>Howdy, {{ user.username }}</h3>
<p>UID: {{ user.uid }}</p>
<!-- <p>Favorite Color: {{ user.countryBirth }} </p> -->
<button (click)="auth.signOut()">Logout</button>
</div>
</ng-template>`,
styleUrls: ['./profil.page.scss'],
})
export class ProfilPage {
constructor(public auth: AuthService ,public user:UserService){}
}
【问题讨论】:
标签: angular typescript firebase google-cloud-firestore ionic4