简体   繁体   中英

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 . My goal is that:

  1. The AuthGuard should be called before the InboxComponent is loaded
  2. This AuthGuard should set the user variable in the AuthService
  3. I should then be able to use the authService.user in the DataService

However, the console.log(this.authService.user) yields undefined although the console.log(authState) in the AuthGuard correctly logs the user information.

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

@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. This is loaded outside the router-module and thus called before the AuthService is called. This in turn caused the DataService before the AuthGuard was called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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