我使用 Angular 7 创建了一个应用程序,并使用 firestore 进行处理。一个用户一切正常。现在,我正在尝试扩展它,并将数据与每个登录用户相关联。我在网上找不到详细的资料。
我收集了一些用户。我想创建一个“假期”集合并将其嵌套在每个用户下,用于他的假期集合。我相信第一步是获取当前登录的用户 uid,并更新我可能拥有的任何功能,以编辑集合,然后是 .doc('current user id')。
这是我用来获取当前用户的 uid 的代码:
this.userID = this.firestore.collection('users').doc(this.auth().user.uid);
预编译器错误:
1- Type 'AngularFirestoreDocument<{}>' is not assignable to type 'string'
2- Cannot invoke an expression whose type lacks a call signature. Type 'AuthService' has no compatible call signatures.
目前数据的结构是这样的:
这是授权服务:
export class AuthService {
user$: Observable<User>;
constructor(
public afAuth: AngularFireAuth,
public afs: AngularFirestore,
public router: Router
) {
// Get the auth state, then fetch the Firestore user document or return null
this.user$ = this.afAuth.authState.pipe(
switchMap(user => {
// Logged in
if (user) {
return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
} else {
// Logged out
return of(null);
}
})
)
}
googleLogin() {
const provider = new auth.GoogleAuthProvider()
return this.oAuthLogin(provider);
}
public oAuthLogin(provider) {
return this.afAuth.auth.signInWithPopup(provider)
.then((credential) => {
this.updateUserData(credential.user)
})
}
public 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 })
}
}
感谢您的帮助。
最佳答案
Google 的官方 答案可以在这里找到 - Get the currently signed-in user - Firebase
下面是一个返回字符串类型 promise 的函数。 promise 使用从 onAuthStateChangedwhich() 返回的用户 uid 以及用户的 firebase auth 对象(displayName...等)的其余部分进行解析。
getCurrentUser(): Promise<string> {
var promise = new Promise<string>((resolve, reject) => {
this.afAuth.auth.onAuthStateChanged(returnedUser => {
if (returnedUser) {
resolve(returnedUser.uid);
} else {
reject(null);
}
});
})
return promise
}
您可以在构造函数或 ngOninit 中调用它:
userDoc: User = null;
constructor() {
this.getCurrentUser().then((userID: string) => {
//here you can use the id to get the users firestore doc
this.afs.collection('users').doc(userID).valueChanges()
.subscribe(userFirestoreDoc => { // remember to subscribe
this.userDoc = userFirestoreDoc;
})
}).catch(nullID => {
//when there is not a current user
this.userDoc = null
})
}
要为嵌套在用户文档中的“假期”添加一个集合,您需要向该用户的 firestore 文档添加一个子集合。我建议仅在用户获得/添加他们的第一个假期后才这样做。您可以简单地在子集合中设置一个文档,如果子集合尚不存在,firestore 将首先创建它,然后添加新的文档(vaction),因此这是您在其中设置新集合和新 vaction 所需的唯一代码那个集合。
this.afs.collection('users').doc(this.userDoc.uid).collection('vacations).add(vactionObject).then(returnedVaction => {
}).catch(error => {
})
关于angular - 通过将数据关联到每个用户来扩展 Angular Firestore 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56013795/