如何在组件中获取当前用户"uid" | Angular 7

How to get current users "uid" in component | Angular 7

努力让每个用户都可以创建和读取自己的数据。 我所做的一切都与本教程中的一样,但它不像那里那样工作: 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 仅在订阅内部有效,returns 在订阅外部未定义。

这是我登录和注销的方式(在另一个组件中):

login() {
  this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider());
}

logout() {
  this.afAuth.auth.signOut();
}

感谢帮助!

您遇到的问题是因为您正在订阅一个可观察对象,并且每当它注意到任何更改时,它都会获取一些带有 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); })

这是因为可观察对象是异步的。由于用户的详细信息是以异步方式带来的。 userId 在 subscribe 方法之外将不可用。所以你需要在订阅块中编写逻辑才能达到预期的结果。

this.afAuth.authState.subscribe(user => {
      if(user) this.userId = user.uid
      //you have to write the logic here.

    }) 

您可以创建一个服务来存储当前用户数据。

interface IUser {
  id: number;
  name: string;
}

@Injectable()
export class CurrentUserService {
  user: IUser;
}

在您的 Firebase 授权代码中的某处:

whenLoggedIn(user: IUser) {
  this.currentUserService.user = user;
}

组件

constructor(public currentUserService: CurrentUserService) {}

模板

{{ currentUserService.user.id }}