返回promise时,Angular APP_INITIALIZER不会延迟应用程序初始化

时间:2018-01-25 19:09:32

标签: angular typescript

我正在尝试在我的root / app模块中使用APP_INITIALIZER来从API(PHP / Laravel)解析经过身份验证的用户。我不想将用户对象存储在localStorage中,因此我只存储JWT令牌,然后让用户进行页面刷新。但是,在承诺从我创建的服务返回以使用APP_INITIALIZER运行之前,将加载一个功能模块(延迟加载)。

//app.module.ts
import { NgModule, APP_INITIALIZER } from '@angular/core';

import { StartupService } from './startup.service';
...
export function initConfiguration(startupService: StartupService) {
  return () => startupService.load();
}

@NgModule({
  ...
  providers: [
     StartupService,
    {
      provide: APP_INITIALIZER,
      useFactory: initConfiguration,
      multi: true,
      deps: [StartupService]
    },
  ],
...


//The startup.service.ts
import { Injectable, Injector } from '@angular/core';
import { AuthService } from 'app/core/auth.service';
@Injectable()
export class StartupService {
  constructor(private injector: Injector) {}

  load(): Promise<boolean> {
    let auth = this.injector.get(AuthService);
    if (auth.isAuthenticated()) {
      auth.getLoggedInUser().subscribe(
        response => {
          //everything from here on is happening after app init
          return Promise.resolve(true);
        },
        error => {
          return Promise.reject(false);
        }
      );
    } else {
      return Promise.resolve(true);
    }
  }
}

一切正常并且已经解决,而不是在我期望的时候(我认为APP_INITIALIZER在任何功能模块加载之前就解决了?

1 个答案:

答案 0 :(得分:2)

问题是您无法从subscribe函数返回任何内容。

您可以尝试这样的事情:

import { AuthService } from 'app/core/auth.service';

@Injectable()
export class StartupService {
  constructor(private auth: AuthService) {}

  load(): Promise<boolean> {
    let promise = new Promise((resolve, reject) => {        
       if (auth.isAuthenticated()) {
          auth.getLoggedInUser().subscribe(response => resolve(true), 
                                           error => reject(false));
       } else {
         resolve(true);
       }
    });

    return promise;

  }
}