在使用Angular2和Firebase启动服务之前,从AuthGuard设置服务值

时间:2016-12-15 21:06:09

标签: authentication angular firebase

我尝试从当前登录的用户获取用户ID,以自定义从 DataService 加载的数据。 我的目标是:

  1. 应在加载InboxComponent之前调用AuthGuard
  2. AuthGuard 应在 AuthService
  3. 中设置用户变量
  4. 然后我应该能够使用DataService中的authService.user
  5. 但是,尽管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 { }
    

1 个答案:

答案 0 :(得分:0)

我终于解决了这个问题。我在app.component.ts文件中调用了我的DataService,以便在导航中获取一些数据。这是在路由器模块外部加载的,因此在调用AuthService之前调用。这反过来导致在调用AuthGuard之前的DataService。