Angular2服务保存类变量值多长时间

时间:2016-11-05 17:31:33

标签: angular firebase firebase-authentication observable

我有一个带有dataservice的Angular2应用程序,该应用程序应根据当前登录的用户显示不同的内容。 我的问题是我的身份验证服务在首次构建后不存储数据值,导致我无法访问其他数据提供程序中的用户ID。

以下是我目前使用2个服务,1个组件和1个authguard完成此操作(见下文)。我期望的逻辑是:

    在启用收件箱路由之前调用
  1. Authguard
  2. Authguard 调用订阅FirebaseAuth的 AuthService 并设置 authState 变量
  3. 如果用户已登录,则 DataService 应始终具有 AuthService
  4. authService.id 的值>

    然而,发生的情况是authService.id产生'未设置',因为即使用户已登录,它似乎永远不会被设置。这可以通过添加{{1}来证明订阅当前打印当前登录用户的 AuthService 中的auth $后。

    因此,我的问题是AuthService中存储的变量 private authState 有多长?在我的DataService中进行其他调用之前,是否还有其他解决方案来获取 authService.id 变量的可观察值?我能想到的一个解决方案是在DataService中为每个数据调用使用switchmap,但这似乎不是最理想的。

    AuthService

    console.log(state)

    AuthGuard

    @Injectable()
    export class AuthService {
    
      private authState: FirebaseAuthState = null;
    
      constructor(private af: AngularFire, public auth$: FirebaseAuth) {
        auth$.subscribe((state: FirebaseAuthState) => {
          this.authState = state;
        });
      }
    
      get authenticated() {
        return this.authState !== null;
      }
    
      get id(): string {
        return this.authenticated ? this.authState.uid : 'Not set';
      }
    }
    

    数据服务

    @Injectable()
    export class AuthGuard implements CanActivate {
      constructor(private authService: AuthService, private router: Router) {}
    
      canActivate(): Observable<boolean> {
        return this.authService.auth$
          .take(1)
          .map(authState => !!authState)
          .do(authenticated => {
            if (!authenticated) {
              this.router.navigate(['/compose']);
            }
          });
      }
    
    }
    

    路线模块

    @Injectable()
    export class EmailService {
    
      private emails: FirebaseListObservable<IEmail[]>;
      private emailUserPath: string;
    
      constructor(private af: AngularFire, authService: AuthService) {
        this.emailUserPath = `/emails/${authService.id}`;
      }
    
      getAllEmails(): FirebaseListObservable<IEmail[]> {
        return this.af.database.list(this.emailUserPath);
      }
    }
    

    应用模块

    const routes: Routes = [
      { path: 'inbox',  component: InboxComponent, canActivate: [AuthGuard] }
    ];
    
    @NgModule({
      imports: [ RouterModule.forChild(routes) ],
      providers: [AuthGuard],
      exports: [ RouterModule ]
    })
    
    export class EmailRoutingModule {}
    

    电子邮件应用模块

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    
    import { AppComponent } from './app.component';
    import { EmailsModule } from './emails/emails.module';
    
    import { AppRoutingModule }     from './app-routing.module';
    import { AngularFireModule, AuthProviders, AuthMethods } from 'angularfire2';
    import { UserSearchComponent } from './shared/user-search/user-search.component';
    import {AuthService} from "./auth/auth.service";
    import {AuthGuard} from "./auth/auth-guard";
    import {EmailRoutingModule} from "./emails/email-routing.module";
    import { UserOrLoginComponent } from './navigation/user-or-login/user-or-login.component';
    import { NavigationListComponent } from './navigation/navigation-list/navigation-list.component';
    
    export const firebaseConfig = {
      apiKey: "hidden",
      authDomain: "hidden",
      databaseURL: "hidden",
      storageBucket: "hidden"
    };
    
    const myFirebaseAuthConfig = {
      provider: AuthProviders.Google,
      method: AuthMethods.Popup
    };
    
    @NgModule({
      declarations: [
        AppComponent,
        UserSearchComponent,
        UserOrLoginComponent,
        NavigationListComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        AppRoutingModule,
        EmailRoutingModule,
        AngularFireModule.initializeApp(firebaseConfig, myFirebaseAuthConfig),
        EmailsModule // I include the Emails module below here
      ],
      providers: [
        AuthService,
        AuthGuard
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

1 个答案:

答案 0 :(得分:0)

只要他们活着,他们就会存储他们的价值观。当您导航到模块外部某个设置服务值的位置时,您将丢失该值。因为您无法再访问具有值集的实例。

服务是每个提供商的单身人士。这意味着如果您需要全局服务/值,则需要在全局级别将其设置为单例。在AuthService处提供AppModule可以解决您的问题。

import { AuthService } from 'path/to/service'

@NgModule({
  imports: [ ],
  providers: [AuthService], //<-- provided globally
  exports: [ ]
})

export class AppModule {}