繁体   English   中英

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

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

我正在尝试为我的应用程序创建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()时,即使用户登录后也未定义。我做错了什么?

这可能是因为在服务器的响应可用之前调用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));
  }

另请参阅在RxJs 5中共享Angular 2 Http网络调用结果的正确方法是什么?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM