LearnToday
LearnToday

Reputation: 2902

How to get isLoggedIn boolan value from auth.service in my app components

I am trying to create firebase authentication for my app.

Here is the auth.service.ts

 private isloggedIn = false;
  constructor(private af: AngularFire, private router: Router) { 
    // this.af.auth.subscribe((auth) => console.log(auth));
    this.af.auth.subscribe(user => {
    if (user) {
      this.isloggedIn = 'true';
    } else {
      this.isloggedIn = 'false';
    }
   });


  }


canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.af.auth.map((auth) =>  {
      if(auth == null) {  
        this.router.navigate(['/auth']);
        return false;
      } else {
        return true;
      }
    }).first()
  }

isLoggedIn () {
 return this.isloggedIn;
}

What I want to do is to observe for authentication state. If that changes, then this.isloggedIn changes too.

Then how do I get the isloggedin auth.service value in my components.

import { AuthService } from './auth.service';
export class SomeComponent implements OnInit {



      constructor(private titleService: Title, private AuthService : AuthService, public toastr: ToastsManager, private af: AngularFire) {

       }

     ngOnInit() {
         this.titleService.setTitle("some component title");
          console.log(this.AuthService.isLoggedIn());
      }

At the moment, when I use this.AuthService.isLoggedIn() gives me undefined even after user is logged in. What am I doing wrong?

Upvotes: 3

Views: 5138

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658245

That's probably because isLoggedIn() is called before the response from your server is available. You need to ensure async calls are properly chained, otherwise you can't be sure a previous one is already completed.

  private isloggedIn:Subject = new BehaviorSubject(false);
  constructor(private af: AngularFire, private router: Router) { 
    this.isLoggedIn = this.af.auth.map(user => { // map instead of subscribe
    if (user) {
      this.isloggedIn = 'true';
    } else {
      this.isloggedIn = 'false';
    }
   });
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.isLoggedIn.map((auth) =>  {
      if(auth == null) {  
        this.router.navigate(['/auth']);
        return false;
      } else {
        return true;
      }
    }).first()
  }
  ngOnInit() {
     this.titleService.setTitle("some component title");
      console.log(this.AuthService.isLoggedIn.subscribe(value => console.log(value));
  }

See also What is the correct way to share the result of an Angular 2 Http network call in RxJs 5?

Upvotes: 2

Related Questions