Angular 4 - Firebase - 检查用户是否已连接

时间:2017-10-11 09:39:43

标签: javascript angular firebase firebase-authentication

我正在使用Firebase与Google进行身份验证。但问题是当我连接并刷新页面时,我想获得Session / CurrentUser。 在文档中我必须使用它:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    console.log(user)
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

这个功能有效,但问题是我不知道tu如何使用observable来等待这个函数的结束。因为这个函数类似于ajax函数,而angular不会等待,所以如果我将用户设置在局部变量中,它将为null。

我已经在stackoverflow中搜索过,但我找不到解决方案

谢谢

2 个答案:

答案 0 :(得分:2)

这个My Answer与@wandrille的解决方案相结合:

您可以使用Subject代替Observable,如下所示:

import { Subject } from "rxjs/Subject";

class AuthService{
   public connectionSubject : Subject<string>() = new Subject<string>();

   firebase.auth().onAuthStateChanged(function(user) {
     if (user) {
       console.log(user)
       this.connectionSubject.next({ state : "connected", user});
     } else {
       this.connectionSubject.next("disconnected");
     }
   });


}

在您的组件中:

 @Component({
   //... 
  })
  class YourComponent{
      constructor(private authService: AuthService){
      }
      ngOnInit(){
         this.authService.connectionSubject.subscribe((data) => {
            if(data.state === 'connected'){
              console.log(data.user);
            }else{
               //...
            }
         });
      }
  }

答案 1 :(得分:2)

我建议你使用angularFire2:

您可以为Auth系统创建服务。

一些例子:

@Injectable()
export class AuthService {

  public firebaseUser : Observable < firebase.User >;
  public currentUser : firebase.User;

  constructor(public afAuth : AngularFireAuth) {

    this.firebaseUser = this.afAuth.authState

  }

  isAuthentificated() {
    return this.firebaseUser
  }

  getCurrentUSer() {
    return this.afAuth.auth.currentUser
  }

  loginUser({email, password}){...some code...}
}

您只需在组件中调用 getCurrentUSer() isAuthentificated()

相关问题