我尝试从当前登录的用户获取用户ID,以自定义从 DataService 加载的数据。 我的目标是:
但是,尽管AuthGuard中的console.log(this.authService.user)
正确记录了用户信息,但console.log(authState)
仍然未定义。
任何可能出错的线索?
身份验证服务
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']);
}
});
}
}
的DataService
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 { }
答案 0 :(得分:0)
我终于解决了这个问题。我在app.component.ts
文件中调用了我的DataService,以便在导航中获取一些数据。这是在路由器模块外部加载的,因此在调用AuthService之前调用。这反过来导致在调用AuthGuard之前的DataService。