我被迫在此处使用Promises with Observables,因为在Angular应用程序中加载数据时,它要求您将APP_INITIALIZER与返回的promise一起使用。这就是为什么我在诺言中创建一个可观察的东西。调试它以查看为什么我的数据未加载到表中后,我发现实例数据成员this.tableDataObs在以后使用getTableModelDataSource(tableName:string)方法被调用时没有任何预订,我无法明白为什么?它在承诺中确实具有价值。发生了什么事?
export class UiDataService {
tableDataObs: Observable<TableModel[]>;
constructor(private httpClient: HttpClient) {
this.tableDataObs = new Observable<TableModel[]>();
}
loadTableData(): Promise<any> {
return new Promise((resolve, reject) => {
this.httpClient
.get('/assets/data/tables.json')
.map((tables: JSON) => {
const tableModels: TableModel[] = this.createTableModels(tables);
this.tableDataObs = of(tableModels); // tableModels has array value here
// this.tableDataObs.subscribe(s => console.log(s)); again subscribing to observable here returns array
})
.subscribe(() => {
resolve(true);
});
});
}
getTableModelDataSource(tableName: string): TableModelDataSource {
this.tableDataObs.subscribe(s => console.log(s)); // this.tableDataObs has nothing to subscribe to here? WHY?
...
}
加载数据调用是从导入到AppModule的SharedModule中进行的
imports ...
export function tableFactory(provider: UiDataService) {
return () => provider.loadTableData();
}
@NgModule({
imports: [
...
],
declarations: [
...
],
entryComponents: [...],
providers: [
...
UiDataService,
{ provide: APP_INITIALIZER, useFactory: tableFactory, deps: [UiDataService], multi: true },
],
exports: [
...
]
})
export class SharedModule {}
和getTableModelDataSource方法调用发生在具有需要数据源的mat表的组件中