LearnToday
LearnToday

Reputation: 2902

How to get value from service constructor in angular2 service

I am trying to work out an Auth Service. I am using this :

@Injectable()
export class AuthService {

  authState: any = null;

  constructor(private afAuth: AngularFireAuth,
              private db: AngularFireDatabase,
              private router:Router) {

            this.afAuth.authState.subscribe((auth) => {
              this.authState = auth;

            });
          }

  // Returns true if user is logged in
  get authenticated(): boolean {
    return this.authState !== null;
  }

The authenticated() function keep giving me false, even if a user is logged in.

When I console.log the authState (this.authState) in the constructor, I do get a value, but outside the constructor , this.authState is null. What am I doing wrong?

Upvotes: 0

Views: 981

Answers (3)

Jayakrishnan
Jayakrishnan

Reputation: 4294

You can use APP_INITIALIZER to wait for the async operation to complete.Please check the below code:

AuthService.ts

  @Injectable()
  export class AuthService {
      authState: any = null;
     constructor(private afAuth: AngularFireAuth,
          private db: AngularFireDatabase,
          private router:Router) {

      }
  loadValue(){
      return new Promise((resolve, reject) => {
           this.afAuth.authState.subscribe((auth) => {
              this.authState = auth;
              resolve(true);
           });
      }); 
  }
  // Returns true if user is logged in
 get authenticated(): boolean {
   return this.authState !== null;
 }
}

app.module.ts

import { NgModule, APP_INITIALIZER } from '@angular/core';

 @NgModule({
  //...
  providers: [AuthService, 
    {
        provide: APP_INITIALIZER,
        useFactory: (authService: AuthService) => () => authService.loadValue(),
        deps: [AuthService],
        multi: true
    }]
  ///....
 })

Hope it helps!!

Upvotes: 0

Rahul Singh
Rahul Singh

Reputation: 19630

Why do you need to Complicate the matter

In your Component where you require the value do this

authState : boolean;

constructor(private afAuth: AngularFireAuth) {

            this.afAuth.authState.subscribe((auth) => {
              this.authState = ( auth !== null ) ? true : false;

            });
          }

Upvotes: 0

Yordan Nikolov
Yordan Nikolov

Reputation: 2678

The better way would be to have separate function

authenticated(): Observable<User> {
    return this.afAuth.authState;
  }

then in your component you can subscribe to this method, like you did in your service constructor

Edited!

Upvotes: 0

Related Questions