如何从我的应用程序组件中的auth.service获取isLoggedIn boolan值

时间:2016-11-30 04:28:59

标签: angular angularfire2

我正在尝试为我的应用创建firebase身份验证。

这是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;
}

我想要做的是观察身份验证状态。如果改变了,那么this.isloggedIn也会改变。

然后如何在我的组件中获取isloggedin auth.service值。

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());
      }

目前,当我使用this.AuthService.isLoggedIn()时,即使用户登录后也未定义。我做错了什么?

1 个答案:

答案 0 :(得分:0)

这可能是因为在您的服务器响应可用之前调用了isLoggedIn()。您需要确保异步调用已正确链接,否则您无法确定之前的调用是否已完成。

  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));
  }

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