angular - 为什么数组引用分配在打字稿中不起作用?
问题描述
我正在开发一个应用程序,我有一个服务和一个组件文件(角度组件的打字稿文件)。我正在做的是从 IndexedDB(Browser) 执行搜索并分配给任何类型的数组,但它不起作用,代码如下:
服务打字稿文件:
// taking a empty array of type any
searchedHistoryArr = [];
// calling method from component typescript file
searchHistoryFromIndexDb(): any[] {
this.indexService.getAll('search', (data) => {
if (data)
for (let i = 0; i < data.length; i++) {
this.searchedHistoryArr.push(data[i]);
}
//console.log(data);
});
return this.searchedHistoryArr;
}
组件文件:这个文件有一些方法,下面写了一行代码。
historyArray=[];
// calling the method of service typescript file
this.historyArray= this.searchService.searchHistoryFromIndexDb()
根据我的预期行为:historyArray 必须具有返回值的引用;但是 HistoryArray 的长度仍然为零。
解决方案
您的方法searchHistoryFromIndexDB
不会返回带有条目的数组,因为您在回调中填充数组,该回调不能同步执行。
因为我不知道您的 IndexedDB 访问实现,我建议您遵循:
// taking a empty array of type any
searchedHistoryArr = [];
// calling method from component typescript file
searchHistoryFromIndexDb(): Promise<any[]> {
const arr: any[] = [];
// Create a new promise, which you can resolve after the IndexedDB returns data
return new Promise((resolve, reject) => {
this.indexService.getAll('search', (data) => {
if (data) {
// Because data is an array, you can just resolve data
resolve(data);
} else {
// Maybe you want to reject the promise in case you don't receive some results
reject('No data available');
}
});
});
}
historyArray=[];
// calling the method of service typecript file
this.searchService.searchHistoryFromIndexDb().then((data) => {
this.historyArray = data;
});
推荐阅读
- loops - 如何使用 host_vars 确保存在多个特定的 cron 作业?
- c++ - 印地UDP通信
- excel - 尽管使用非 Excel 2003 函数和文件,但 MS Access 数据导入 65000 行限制的问题
- vba - 从不同的表中循环到另一张中
- jasper-reports - 当详细信息部分中有两个波段时,如何强制第一个详细信息波段打印在页面顶部?
- robotframework - 如何使用 Robot Framework RESTinstance 库验证 JSON 结果
- mysql - 动态创建表时如何避免SQL注入风险?
- python - 从 Django 1.8 升级到 1.9 时出现 ValueError
- reactjs - 如何从不是主应用程序页面的页面路由到另一个页面
- c - C 代码的问题,在 10 月的最后一个星期日更改标志以进行夏令时