试图使每个用户都能创建和读取自己的数据。我所做的一切都与本教程中的相同,但不像本教程那样工作:https://angularfirebase.com/lessons/managing-firebase-user-relationships-to-database-records/
我的数据库结构如下:
-|items
-|userId
-|itemId这是我的服务:
userId: string;
constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth) {
this.afAuth.authState.subscribe(user => {
if(user) this.userId = user.uid
})
}以及从数据库获取项的服务中的示例函数:
getRelays(): Observable<any[]> {
if(!this.userId) return;
this.relaysRef = this.db.list('relays/' + this.userId)
return this.relaysRef.snapshotChanges().pipe(
map(changes =>
changes.map(c => ({ $key: c.payload.key, ...c.payload.val() }))
)
);
}我希望访问组件中的当前用户id,这样我就可以根据当前用户获取项,但是变量userId只在订阅中工作,并返回未定义的外部项。
这就是我登录和退出(在另一个组件中)的方式:
login() {
this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider());
}
logout() {
this.afAuth.auth.signOut();
}谢谢你帮忙!
发布于 2019-01-03 21:02:16
这是因为可观测值是异步的。因为用户的详细信息是以异步方式带来的。在订阅方法之外,userId将不可用。因此,您需要在订阅块中写入逻辑,以实现所需的结果。
this.afAuth.authState.subscribe(user => {
if(user) this.userId = user.uid
//you have to write the logic here.
}) 发布于 2019-01-03 20:27:47
您所面临的问题是因为您订阅了一个可观察的,并且每当它注意到任何更改时,它都会获得一些id数据,并更改"uid“的值。处理此问题的最佳方法是将"responce.uid“存储到本地存储中,并在需要时从本地存储获取该id。像这样
this.api.getUser(res.user.uid).subscribe(resp => {
if (resp) {
localStorage.setItem('uid', res.user.uid);
localStorage.setItem('email', this.user.email); })发布于 2019-01-03 22:18:56
您可以创建一个存储当前用户数据的服务。
interface IUser {
id: number;
name: string;
}
@Injectable()
export class CurrentUserService {
user: IUser;
}在您的基本火力代码中的某个位置:
whenLoggedIn(user: IUser) {
this.currentUserService.user = user;
}组件
constructor(public currentUserService: CurrentUserService) {}模板
{{ currentUserService.user.id }}https://stackoverflow.com/questions/54028662
复制相似问题