You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic6+Angular15调用SQLite报Cannot read properties of undefined错误

问题排查与修复

错误根源

Cannot read properties of undefined (reading 'then') 说明你调用.then()的对象是undefined,结合你的代码,主要有几个触发点:

  • 数据库Provider里的db.create()因为this.dbName为空字符串,返回了undefined而非有效Promise
  • 搜索服务中RxJS操作符写法错误,catchError被错误嵌套在map参数里
  • Promise链中的catch块只打印错误却不抛出,导致Observable流异常中断

修复步骤

1. 补全数据库名称

你的组件里dbName初始化为空字符串,数据库Provider用这个空名称创建数据库必然出问题。先给数据库Provider指定有效名称:

// 数据库Provider代码
private dbName: string = 'app_db.db'; // 替换成你的实际数据库文件名

public getDistricts(): Observable<any> {
  let db = new SQLite();
  return from(
    db.create({
      name: this.dbName,
      location: "default"
    }).then((connexion: SQLiteObject) => {
      return connexion.executeSql("SELECT * FROM district ORDER BY name", [])
        .then((data: any) => data)
        .catch((err: any) => {
          console.log(err);
          throw err; // 抛出错误让Observable捕获
        })
    }).catch((e: any) => {
      console.log(e);
      throw e; // 传递错误到上层订阅
    })
  );
}

2. 修正RxJS操作符结构

搜索服务里的catchError不能放在map的参数里,要作为pipe的独立操作符:

// 搜索服务TS代码
public getDistricts(): Observable<any> {
  return this.databaseProvider.getDistricts().pipe(
    map((res: any) => res),
    catchError((error: any) => throwError(() => error))
  );
}

3. 保证错误正确传递

Promise链里的catch块不能只打日志,必须抛出错误,这样from转换的Observable才能把错误传递给订阅者,避免Promise链中断后返回undefined。

额外检查

  • 确认安卓设备上已安装cordova-sqlite-storage插件:运行cordova plugin list查看
  • 确保数据库里存在district表,可通过Edge调试工具查看数据库内容

内容的提问来源于stack exchange,提问作者testyahoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 14:30:06