![](/img/trans.png)
[英]AuthGuard: OnAuthStateChanged VS check token in Angular 5 + Firebase
[英]Set value in service from AuthGuard before service is initiated with Angular2 and Firebase
我正在尝试从当前登录的用户获取用户ID,以自定义从DataService加载的数据。 我的目标是:
但是,尽管console.log(authState)
的console.log(authState)
正确记录了用户信息,但console.log(this.authService.user)
产生的不确定。
关于可能出什么问题的任何线索?
认证服务
export class AuthService {
public user: any;
constructor(private af: AngularFire, public auth$: FirebaseAuth) {
console.log("Auth service state:", this.authState);
}
AuthGuard
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): Observable<boolean> {
return this.authService.auth$
.take(1)
.map(authState => {
console.log(authState)
this.authService.setUser(authState);
return !!authState })
.do(authenticated => {
if (!authenticated) {
this.router.navigate(['/error']);
}
});
}
}
数据服务
export class DataService {
private userPath: string;
constructor(private af: AngularFire, private authService: AuthService) {
console.log(this.authService.user);
}
路由器
const routes: Routes = [
{ path: 'inbox', component: InboxComponent, canActivate: [AuthGuard] }
应用模块
@NgModule({
declarations: [
InboxComponent
],
imports: [
EmailsModule
],
providers: [
AuthService,
AuthGuard
],
bootstrap: [AppComponent]
})
export class AppModule { }
我终于解决了。 我在app.component.ts
文件中调用了DataService,以在导航中获取一些数据。 它被加载到路由器模块外部,因此在调用AuthService之前被调用。 这又导致了在调用AuthGuard之前的DataService。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.