首页 > 解决方案 > 为什么数组引用分配在打字稿中不起作用?

问题描述

我正在开发一个应用程序,我有一个服务和一个组件文件(角度组件的打字稿文件)。我正在做的是从 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 的长度仍然为零。

标签: angular

解决方案


您的方法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;
});

推荐阅读