试图让Angular 2在渲染之前等待数据加载

时间:2018-04-24 16:45:49

标签: angular angular-promise

我需要在初始渲染之前加载多个XML文件。我拥有的是什么 app.module.ts

import { DataProvider } from './xml-provider'

export function dataProviderFactory(provider: DataProvider) {
  return () => provider.load();
}

providers: [
    DataProvider,
    { provide: APP_INITIALIZER, useFactory: dataProviderFactory, deps: [DataProvider], multi: true }
  ],

然后在xml-provider.ts

load(){
  let promises:Promise<any>[] = [];
  promises.push(this.loader1());
  promises.push(this.loader2());

  Promise.all(promises).then(
    (values) => { 
      console.log("Promise all finished: " + values);
      return true; 
    }
  );
}



  private loader1():Promise<any> {
    return new Promise((resolve, reject) => {
      this.http.get('assets/data.xml')
        .map(res => {
          let data;
          parseString(res.text(), { trim: true } ,function (err, result) {
            data = result.xml;
          });
          this.xmldata = data;
        })
        .subscribe(data => { resolve(true); })
    })    
  }

当我将loader1作为加载函数时,Angular确实等到文件加载完毕并且一切正常。现在我已经添加了更多文件,它不会等待加载返回。我错过了什么让app.module.ts等到所有文件都加载完毕?

1 个答案:

答案 0 :(得分:0)

return前面缺少Promise.all。我希望它解决了这个问题。

load(){
  let promises:Promise<any>[] = [];
  promises.push(this.loader1());
  promises.push(this.loader2());

  //// Missing return was here
  return Promise.all(promises).then(
    (values) => { 
      console.log("Promise all finished: " + values);
      return true; 
    }
  );
}