0

i'm trying to setup Angular application with Firebase authentication. My goal now is to obtain client user's token and data during App Initialization.

In App module I have setup AuthServise as APP_INITIALIZER

 providers: [
    AuthService,
    {
      provide: APP_INITIALIZER,
      useFactory:loadAuthService ,
      deps: [AuthService],
      multi: true
    },

export function loadAuthService(authService: AuthService): Function 
{
  return () => { return authService.load() }; 
}

And my AuthService with 'Load' function looks like this


    private _token: BehaviorSubject<string>  = new BehaviorSubject<string>(null);
    private _fUser: BehaviorSubject<firebase.User> = new BehaviorSubject<firebase.User>(null);

  // Returns true when user is looged in localStorage of the client
  get isLoggedIn(): boolean {
    return (this.localStorageUser !== null) ? true : false;
  }

  get localStorageUser(): firebase.User {
    return JSON.parse(localStorage.getItem('user'));
  }

  get token(): string {
    return this._token.getValue();
  }

  set token(token: string) {
    this._token.next(token);
  }

  get fUser(): firebase.User {
    return this._fUser.getValue();
  }

  set fUser(fUser: firebase.User){
    this._fUser.next(fUser);
  }

    /**
     * Called and waited on during app initialiation.
     * Initializing app with auth service
     */
    public async load()
    {
      console.log('Initializing app with auth service');
      //Check whether user is in client's local storage
      if (this.isLoggedIn){
        this.fUser = this.localStorageUser;
        const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${this.fUser.uid}`);
        try {
          this.token = await this.fUser.getIdToken();
        } catch (error) {
          console.log('getting token error', error);
        }
      }
    }

I don't know why i'm getting error 'this.fUser.getIdToken is not a function' Any suggestions please ? Thank you in forward.

1 Answer 1

2

When you store an object in localStorage it gets serialized. You cannot store a firebase User object like that. And it's also not necessary, because firebase has its own state persistence built-in.

You need to set:

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)

Indicates that the state will be persisted even when the browser window is closed or the activity is destroyed in React Native. An explicit sign out is needed to clear that state. Note that Firebase Auth web sessions are single host origin and will be persisted for a single domain only.

You can also think about using the official @angular/fire package, which has nice observables and is made specifically for angular

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for hints. I',m using @angular/fire ... but from your answer I still dont know how to get the token correctly during app initialization. I just need promise with token result, not observable with token.
Ok I found the solution with combination of setting Persistence and getting Promise with onAuthStateChanged
@emihud right :) glad I could help a bit, nice that you found it out yourself!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.