如何使用角度5中的APP_INITIALIZER正确加载对象以进行缓存?

时间:2018-04-08 04:16:01

标签: angular

我开发了一个服务,它在启动时加载对象,但这些对象不是 在缓存中可用。

在NgModule上面的setupApp函数

 export function setupApp(setup: AppLoadService ) {
     return () => setup.initliaze();
 }

@NgModule({
    imports: [

NgModule

 providers: [
        AppLoadService ,
        { 
            provide: APP_INITIALIZER,
            useFactory: setupApp,
            deps: [AppLoadService ],
            multi: true
         },

AppLoadService ...

@Injectable()
export class AppLoadService  {

  private url = ...

  public countries: Country[]  = [];

  constructor(private http: HttpClient) {}

  public initliaze() {
    this.initCountries();
  }

  public initCountries() {
    if (this.countries.length == 0) {
      this.http.get<Country[]>(`${this.url}`)
      .subscribe(data => { this.countries = data; },
          err => console.error(err),
          () => console.log('done load countries')
      )
    }
  }

  public getCountries() {
    console.log(this.countries)
    return this.countries;
  }
}

调用getCountries()方法时,返回空数组。我需要AppLoadService作为缓存服务,任何想法如何实现这个?

更新 我已将initliaze功能更改为此功能,现在看起来缓存正在运行:

 initliaze(): Promise<any> {
    return new Promise((resolve, reject) => {
          console.log(`initializeApp:: inside promise`);
          this.initCountries();
          setTimeout(() => {
            console.log(`initializeApp:: inside setTimeout`);
            // doing something

            resolve();
          }, 3000);
        });
  }

0 个答案:

没有答案