gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:35:05 26 4
gpt4 key购买 nike

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

最佳答案

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

关于angular - 如何从我的应用程序组件中的 auth.service 获取 isLoggedIn bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40880317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com