onAuthStateChanged返回取消订阅,我想返回currentUser [英] onAuthStateChanged return unsubscribe, I want to return currentUser

查看:79
本文介绍了onAuthStateChanged返回取消订阅,我想返回currentUser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Firebase(5.2)的Angular项目(6.0)中.我正在使用该功能:

I am in an Angular project (6.0) using firebase (5.2). I am using the function:

firebase.auth().onAuthStateChanged

此函数返回一个firebase.Unsubscribe,我不掌握.我只知道与Observables,Subject和Promises一起工作.

this function returns a firebase.Unsubscribe, which I don't master. I just know to work with Observables, Subjects and Promises.

我想将此功能作为一种可观察的方式使用,例如,每当我获得currentUser时,我都订阅它.

I would like to use this function as a observable, like, I subscribe to it whenever I get the currentUser back.

到目前为止,我已经尝试将其包装为可观察的:

So far, I've tried to wrap it a observable:

auth.service.ts

auth.service.ts

  loadUser() {
    return Observable.create((observer: Observer<any>) => {
      firebase.auth().onAuthStateChanged(
        currentUser => { return currentUser }
      )
    })
  }

每当我开始我的角度申请时我都会订阅:

and I subscribe whenever I start my angular application:

在ngOnInit中:

in ngOnInit:

this.authService.loadUser()
  .subscribe(
    response => {
      console.log("response");
      console.log(response);
    },
    error => {
      console.log("error");
      console.log(error);
    }
  )

但是订阅永远不会触发.我没有包装Firebase的功能. 1.我不太了解他们为什么返回firebase.unsubscribe. 2.如何解决挑战?

But the subscription is never triggered. I am not wrapping right the function of Firebase. 1. I don't really understand why they return a firebase.unsubscribe. 2. How can I solve the challenge?

谢谢

推荐答案

如果您考虑使用库 angularfire2 (我真的建议至少在您的应用程序中尝试一下),您可以利用诸如

If you consider using the library angularfire2 (I'd really recommend at least trying it out for your application), you can take advantage of injectable services such as AngularFireAuth to track authentication state as an observable. Below is example of using AngularFireAuth from angularfire2 to get current user information, check if a user is logged in, and signin/signout

import { firebase } from '@firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';
import { User, UserCredential } from '@firebase/auth-types';
import { Observable } from 'rxjs';
import { take, map } from 'rxjs/operators';
...

user: Observable<User>;

constructor(private afAuth: AngularFireAuth) {
  this.user = this.afAuth.authState;
}

getUser(): Observable<User> {
  return this.user.pipe(take(1));
}

isLoggedIn(): Observable<boolean> {
  return this.user.pipe(
    take(1),
    map(authState => !!authState)
  );
}

logUser() {
  this.getUser().subscribe(user => console.log(user));
}

login(): Promise<UserCredential> {
  return this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
}

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

希望有帮助!

这篇关于onAuthStateChanged返回取消订阅,我想返回currentUser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆