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

Angular14+Ionic6首次加载引导页实现报错求助

问题解决:Property 'then' does not exist on type 'void'

错误根源

你的StorageService里的getValue方法没有返回异步操作的Promise——它只是在内部执行this.storage.get()并打印结果,但没把这个Promise返回给调用者。所以当守卫里调用this.storageService.getValue('first_time').then(...)时,TypeScript会报错,因为void类型不存在then方法。

修复步骤

1. 修正StorageService的异步方法

修改storage.service.ts,让getValue返回包含存储值的Promise,同时setValue也返回Promise以确保异步操作完成:

export class StorageService {
  constructor(
    private storage: Storage
  ) {
    this.init();
  }

  async init() {
    await this.storage.create();
  }

  // 返回Promise,确保调用者能追踪异步操作
  setValue(key: 'first_time', value: 'done'): Promise<void> {
    return this.storage.set(key, value);
  }

  // 返回包含存储值的Promise,供调用者处理结果
  getValue(key: 'first_time'): Promise<string | null> {
    return this.storage.get(key).then((value) => {
      console.log(value);
      return value; // 必须返回获取到的值,否则调用者拿不到结果
    });
  }
}

2. 简化路由守卫逻辑

守卫里不需要手动创建新Promise,直接返回getValue处理后的Promise即可,Angular会自动等待异步操作完成:

import { ActivatedRouteSnapshot, CanActivate, Router } from '@angular/router';
import { StorageService } from '../services/storage.service';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class FirstLoadGuard implements CanActivate {
  constructor(
    private storageService: StorageService,
    private router: Router
  ) {}

  canActivate(route: ActivatedRouteSnapshot): Promise<boolean> {
    return this.storageService.getValue('first_time').then((value) => {
      if (value !== null) {
        this.router.navigateByUrl('/login');
        return false;
      } else {
        // 链式调用确保存储状态设置完成后,再允许进入欢迎页
        return this.storageService.setValue('first_time', 'done').then(() => true);
      }
    });
  }
}

额外提示

Ionic的Storage所有操作都是异步的,所以相关方法必须返回Promise,这样才能保证调用者能正确处理异步流程,避免出现状态不一致或跳转异常的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:23:31