试图让 Angular 2 在渲染之前等待数据加载
trying to get Angular 2 to wait for data(s) to load before rendering
我有多个 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 会一直等到文件加载完毕,一切正常。现在我已经添加了更多文件,它不会等待加载到 return。我错过了什么让 app.module.ts 等待所有文件加载完毕?
Promise.all
前面少了一个return
。我希望它能解决问题。
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;
}
);
}
我有多个 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 会一直等到文件加载完毕,一切正常。现在我已经添加了更多文件,它不会等待加载到 return。我错过了什么让 app.module.ts 等待所有文件加载完毕?
Promise.all
前面少了一个return
。我希望它能解决问题。
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;
}
);
}