1
我在这里跟着AngularFire教程:https://angularfirebase.com/lessons/google-user-auth-with-firestore-custom-data/。我的问题是:我将如何获取当前登录的用户的UID和displayName在不同的组件?我已经导入并注入AuthService(下面的服务),但是如何访问Firestore中的这些字段?以下是相关的代码。如何获得观察值?
@Injectable()
export class AuthService {
user: Observable<User>;
constructor(private afAuth: AngularFireAuth,
private afs: AngularFirestore,
private router: Router) {
//// Get auth data, then get firestore user document || null
this.user = this.afAuth.authState
.switchMap(user => {
if (user) {
return this.afs.doc<User>(`users/${user.uid}`).valueChanges()
} else {
return Observable.of(null)
}
})
}
googleLogin() {
const provider = new firebase.auth.GoogleAuthProvider()
return this.oAuthLogin(provider);
}
private oAuthLogin(provider) {
return this.afAuth.auth.signInWithPopup(provider)
.then((credential) => {
this.updateUserData(credential.user)
})
}
private updateUserData(user) {
// Sets user data to firestore on login
const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.uid}`);
const data: User = {
uid: user.uid,
email: user.email,
displayName: user.displayName,
photoURL: user.photoURL
}
return userRef.set(data)
}
signOut() {
this.afAuth.auth.signOut().then(() => {
this.router.navigate(['/']);
});
}
}
这个奇妙的作品, 非常感谢。 – FiringBlanks