Access authenticated data with AngularFire2

孤者浪人 提交于 2019-12-03 21:25:49

use arrow function => to preserve this keyword:

 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!")
          }
        });
      }
    }

you can do better :

 @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));
      }
    }

use ChangeDetectorRef to force angular to update the view :

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{
            //...
          }
        });

 }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!