简体   繁体   English

在使用Angular2和Firebase启动服务之前,请通过AuthGuard在服务中设置值

[英]Set value in service from AuthGuard before service is initiated with Angular2 and Firebase

I'm trying to get the user ID from the currently logged in user to customize the data loaded from my DataService . 我正在尝试从当前登录的用户获取用户ID,以自定义从DataService加载的数据。 My goal is that: 我的目标是:

  1. The AuthGuard should be called before the InboxComponent is loaded 在加载InboxComponent之前应调用AuthGuard
  2. This AuthGuard should set the user variable in the AuthService AuthGuard应设置用户变量在AuthService
  3. I should then be able to use the authService.user in the DataService 然后,我应该能够在DataService中使用authService.user

However, the console.log(this.authService.user) yields undefined although the console.log(authState) in the AuthGuard correctly logs the user information. 但是,尽管console.log(authState)console.log(authState)正确记录了用户信息,但console.log(this.authService.user)产生的不确定。

Any clues on what could be wrong? 关于可能出什么问题的任何线索?

Authentication Service 认证服务

export class AuthService {

  public user: any;

  constructor(private af: AngularFire, public auth$: FirebaseAuth) {
    console.log("Auth service state:", this.authState);
  }

AuthGuard 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);
  }

Router 路由器

const routes: Routes = [
  { path: 'inbox',  component: InboxComponent, canActivate: [AuthGuard] }

App Module 应用模块

@NgModule({
  declarations: [
    InboxComponent
  ],
  imports: [
    EmailsModule
  ],
  providers: [
    AuthService,
    AuthGuard
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

I finally resolved this. 我终于解决了。 I had a call to my DataService in my app.component.ts file to get some data in my navigation. 我在app.component.ts文件中调用了DataService,以在导航中获取一些数据。 This is loaded outside the router-module and thus called before the AuthService is called. 它被加载到路由器模块外部,因此在调用AuthService之前被调用。 This in turn caused the DataService before the AuthGuard was called. 这又导致了在调用AuthGuard之前的DataService。

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

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