使用 AngularFire2 访问经过身份验证的数据

Access authenticated data with AngularFire2

我在 Angular2 项目中使用 AngularFire2 来完成一项非常基本的任务,登录然后在页面上显示登录用户信息。

我遇到的看似简单的问题是我需要知道用户 UID 才能从 Firebase 请求数据(我的权限状态只能访问具有自己的 UID 的“/users”内的密钥 - 非常标准)。

我发现为了获得 UID,我需要订阅 af.auth observable,然后在里面使用 af.auth.uid 请求用户数据——我已经成功完成了。

我还注意到 af.database.object 创建了另一个可观察对象,理论上我可以通过在我的 HTML 中使用 Asyc 进行管道访问。问题是我似乎无法在我的应用程序的其他任何地方(特别是在 HTML)获得对在 auth.subscribe 中获得的用户数据的引用。

我可以console.log用户的订阅,这确认我正在获取数据。

请纠正我的理解或教我如何访问这些数据,我对 Typescript 和 Observables 的概念非常陌生。

Javascript Angular 2 分量

export class AppComponent {
  title = 'Webroot';
  user: FirebaseObjectObservable<any>;
  constructor(public af: AngularFire) {
    af.auth.subscribe(function(auth){
      if(auth != null){
        this.user = af.database.object("users/"+auth.uid)
        this.user.subscribe(user => console.log(user));
      }
      else{
        console.log("Auth is Null!")
      }
    });
  }
}

HTML

<div> {{ (user | async | json) }} </div>

使用箭头函数=>保留this关键字:

 export class AppComponent {
      title = 'Webroot';
      user: FirebaseObjectObservable<any>;
      constructor(public af: AngularFire) {
        af.auth.subscribe((auth)=>{
          if(auth != null){
            this.user = af.database.object("users/"+auth.uid)
            this.user.subscribe(user => console.log(user));
          }
          else{
            console.log("Auth is Null!")
          }
        });
      }
    }

你可以做得更好:

 @Injectable()
  class UserService{
     constructor(private af: AngularFire) {}

     getUser(){
         return this.af.auth.switchMap((auth)=>{
            return this.af.database.object("users/"+auth.uid)
         });
     }
}



export class AppComponent {
      title = 'Webroot';
      user: FirebaseObjectObservable<any>;
      constructor(public userService: UserService) {
        this.userService
            .getUser()
            .subscribe(user => console.log(user));
      }
    }

使用ChangeDetectorRef强制angular更新视图:

import { ChangeDetectorRef } from '@angular/core';

constructor(private af: AngularFire,public userService: UserService,private ref: ChangeDetectorRef) { }

 init(){
   this.userPublic = "Init";
   af.auth.subscribe((auth)=>{
          if(auth != null){
            this.getData(auth);
            this.userPublic = "Finish";
            this.ref.detectChanges(); 
          }
          else{
            //...
          }
        });

 }
}