我的Firebase演示应用程序有问题。我通过Google身份验证登录,并且具有userId,但是当我导航到该页面时,它变得不确定。
我的身份验证服务如下:
export class AuthService {
user$: Observable<User>;
currentUserId: string;
constructor(
private afAuth: AngularFireAuth,
private afs: AngularFirestore,
private router: Router
) {
this.user$ = this.afAuth.authState.pipe(
switchMap((user) => {
// Logged in
if (user) {
this.currentUserId = user.uid;
return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
} else {
// Logged out
this.currentUserId = null;
return of(null);
}
})
);
}
async googleSignin() {
const provider = new auth.GoogleAuthProvider();
const credential = await this.afAuth.signInWithPopup(provider);
return this.updateUserData(credential.user);
}
private updateUserData(user) {
// Sets user data to firestore on login
const userRef: AngularFirestoreDocument<User> = this.afs.doc(
`users/${user.uid}`
);
const data = {
uid: user.uid,
email: user.email,
displayName: user.displayName,
photoURL: user.photoURL,
};
return userRef.set(data, { merge: true });
}
}
和处理待办事项集合的“待办事项服务”:
export class TodoService {
todos: Observable<Todo[]>;
userId: string;
constructor(private afs: AngularFirestore, private auth: AuthService) {
this.auth.user$.subscribe((x) => {
this.userId = x.uid;
console.log("this.userid: " + this.userId);
});
this.todos = this.afs
.collection<Todo>("todos")
.valueChanges()
.pipe(
switchMap((x) => {
return of(x.filter((e) => e.userId === this.userId));
})
);
}
add(todo: Todo) {
const ref = this.afs.collection<Todo>("todos");
todo.userId = this.userId;
ref.add(todo);
}
当我导航到列出待办事项的/ todo页面时,待办事项服务中的userId为undefined
。
也许我有概念上的错误。
当我过滤“我的待办事项”时,如何确保userId已经“加载”?