Angular 8 accountService在loginService中未定义

问题描述 投票:0回答:1

如您所见,我们希望我们的应用程序延迟加载管理模块。当我们在app.module.ts中包含管理模块时,它工作正常,但这并不是延迟加载方式。我对吗?因此,从app.module.ts中删除adminmodule这是问题loginService有一个名为accountService的依赖项服务。启动此应用程序时,accountService始终是未定义的。我不知道管理模块如何影响服务。有人可以给我一些建议吗?谢谢!

下面是相关代码(据我了解)app.module.ts

 ...imports

 @NgModule({
  imports: [
    BrowserModule,
    NgxWebstorageModule.forRoot({ prefix: 'jh', separator: '-' }),
    NgJhipsterModule.forRoot({
      // set below to true to make alerts look like toast
      alertAsToast: false,
      alertTimeout: 5000,
      i18nEnabled: true,
      defaultI18nLang: 'en'
    }),
    SharedModule.forRoot(),
    CoreModule,
    HomeModule,
    AccountModule,
    LayoutRoutingModule,
    NgIdleModule.forRoot(),
    BrowserAnimationsModule,
    // AdminModule,
    ApprovalModule,
    BatchJobModule,
    ShowCaseModule,
    BatchJobShowCaseModule,
    // jhipster-needle-angular-add-module JHipster will add new module here
    EntityModule,
    AppRoutingModule
  ],
  declarations: [IcMainComponent, NavbarComponent, ErrorComponent, PageRibbonComponent, ActiveMenuDirective, FooterComponent],
  providers: [
    {
      provide: LocationStrategy,
      useClass: HashLocationStrategy
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthExpiredInterceptor,
      multi: true
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ErrorHandlerInterceptor,
      multi: true
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: NotificationInterceptor,
      multi: true
    }
  ],
  bootstrap: [IcMainComponent]
})
export class AppModule {
  constructor(private dpConfig: NgbDatepickerConfig) {
    this.dpConfig.minDate = { year: moment().year() - 100, month: 1, day: 1 };
  }
}

app.route.ts

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { errorRoute, navbarRoute } from './layouts';
import { DEBUG_INFO_ENABLED } from 'app/app.constants';

const LAYOUT_ROUTES = [navbarRoute, ...errorRoute];

@NgModule({
  imports: [
    RouterModule.forRoot(
      [
        {
          path: 'admin',
          loadChildren: './admin/admin.module#AdminModule'
        },
        ...LAYOUT_ROUTES
      ],
      // { enableTracing: DEBUG_INFO_ENABLED }
    )
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}

loginService.ts

.. imports

@Injectable({ providedIn: 'root' })
export class LoginService {
  constructor(private accountService: AccountService, private authServerProvider: AuthServerProvider) {
    console.log('loginSerive constr');
    console.log(this.accountService); *-------undefined*
  }

  login(credentials, callback?) {
    const cb = callback || function() {};

    return new Promise((resolve, reject) => {
      this.authServerProvider.login(credentials).subscribe(
        data => {
          this.accountService.identity(true).then(account => {
            resolve(data);
          });
          return cb();
        },
        err => {
          this.logout();
          reject(err);
          return cb(err);
        }
      );
    });
  }

  loginWithToken(jwt, rememberMe) {
    return this.authServerProvider.loginWithToken(jwt, rememberMe);
  }

  logout() {
    console.log(this.accountService);  *-------undefined*
    this.authServerProvider.logout().subscribe(() => 
          this.accountService.authenticate(null)
    );
  }
}

account.service.ts

...imports
@Injectable({ providedIn: 'root'})
export class AccountService {
  private userIdentity: any;
  private authenticated = false;
  private authenticationState = new Subject<any>();

  constructor(
    private languageService: JhiLanguageService,
    private sessionStorage: SessionStorageService,
    private _menuService: IcMenuService,
    private http: HttpClient
  ) {}

  fetch(): Observable<HttpResponse<Account>> {
    return this.http.get<Account>(SERVER_API_URL + 'api/account', { observe: 'response' });
  }

  save(account: any): Observable<HttpResponse<any>> {
    return this.http.post(SERVER_API_URL + 'api/account', account, { observe: 'response' });
  }

  authenticate(identity) {
    this.userIdentity = identity;
    this.authenticated = identity !== null;
    console.log(this.authenticated);
    this.authenticationState.next(this.userIdentity);
  }

  hasAnyAuthority(authorities: string[]): boolean {
    if (!this.authenticated || !this.userIdentity || !this.userIdentity.authorities) {
      return false;
    }

    for (let i = 0; i < authorities.length; i++) {
      if (this.userIdentity.authorities.includes(authorities[i])) {
        return true;
      }
    }

    return false;
  }

  hasAuthority(authority: string): Promise<boolean> {
    if (!this.authenticated) {
      return Promise.resolve(false);
    }

    return this.identity().then(
      id => {
        return Promise.resolve(id.authorities && id.authorities.includes(authority));
      },
      () => {
        return Promise.resolve(false);
      }
    );
  }

  identity(force?: boolean): Promise<Account> {
    if (force) {
      this.userIdentity = undefined;
    }

    // check and see if we have retrieved the userIdentity data from the server.
    // if we have, reuse it by immediately resolving
    if (this.userIdentity) {
      return Promise.resolve(this.userIdentity);
    }

    // retrieve the userIdentity data from the server, update the identity object, and then resolve.
    return this.fetch()
      .toPromise()
      .then(response => {
        const account: Account = response.body;
        if (account) {
          this.userIdentity = account;
          this.authenticated = true;
          console.log('--------------------I have been changed!!!-----------------------')
          // After retrieve the account info, the language will be changed to
          // the user's preferred language configured in the account setting
          if (this.userIdentity.langKey) {
            const langKey = this.sessionStorage.retrieve('locale') || this.userIdentity.langKey;
            this.languageService.changeLanguage(langKey);
          }
        } else {
          this.userIdentity = null;
          this.authenticated = false;
        }
        this.authenticationState.next(this.userIdentity);
        this._menuService.updateMenuByRoutes(<Routes>account.menus);
        return this.userIdentity;
      })
      .catch(err => {
        this.userIdentity = null;
        this.authenticated = false;
        this.authenticationState.next(this.userIdentity);
        return null;
      });
  }

  isAuthenticated(): boolean {
    return this.authenticated;
  }

  isIdentityResolved(): boolean {
    return this.userIdentity !== undefined;
  }

  getAuthenticationState(): Observable<any> {
    return this.authenticationState.asObservable();
  }

  getImageUrl(): string {
    return this.isIdentityResolved() ? this.userIdentity.imageUrl : null;
  }

  getMenus(): any {
    return this.isIdentityResolved() ? this.userIdentity.menus : null;
  }

  getSessionTimeoutMin(): Observable<HttpResponse<any>> {
    return this.http.get(SERVER_API_URL + 'api/session-timeout-min', { observe: 'response' }).pipe(
      map((resp: HttpResponse<any>) => {
        return resp;
      })
    );
  }
}
service jhipster angular8
1个回答
0
投票

您必须告诉Angular实例化accountService在loginService之前可用(已实例化)。

因此,您将其声明为模块的提供者。

app.module.ts中添加

providers: [AccountService],
© www.soinside.com 2019 - 2024. All rights reserved.