我正在开发一个应用程序,我有一个服务和一个组件文件(一个角文件)。我正在做的是从IndexedDB(Browser)中执行搜索并将其分配给任何类型的Array,但是它不起作用,代码如下:
服务打字稿文件:
// 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的长度仍然为零。
答案 0 :(得分:0)
您的方法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;
});