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

如何从Observable中返回值?subscribe回调返回布尔值报类型错误怎么解决

报错原因

报错A function whose declared type is neither 'void' nor 'any' must return a value.的触发原因有两点:

  1. 你声明了isLoggedIn方法的返回值类型为boolean,但整个方法外层没有任何返回语句,你写的return true/return false都是subscribe回调函数的返回值,完全不作用于外层的isLoggedIn方法。
  2. http.get属于异步网络请求,你无法同步拿到请求结果直接返回布尔值,同步返回的写法本身不符合异步逻辑,也不要在该方法内部直接调用subscribe,一旦订阅就没法把异步结果传递给方法调用方。

解决方案

方案1:返回Observable(推荐,符合Angular HttpClient的设计逻辑)

直接把请求流处理后返回,由调用方订阅拿结果:

// 先导入需要的rxjs依赖
import { map, catchError } from 'rxjs/operators';
import { of, Observable } from 'rxjs';

public isLoggedIn(): Observable<boolean> {
  const url = `${this.endPoint}/me`;
  return this.http.get<any>(url).pipe(
    // 请求成功返回true
    map(() => true),
    // 请求失败返回false
    catchError(() => of(false))
  );
}

调用示例:

this.isLoggedIn().subscribe(isLogin => {
  // 在这里处理登录状态相关逻辑
  console.log('是否登录:', isLogin);
})

方案2:转为Promise用async/await返回

如果你习惯用Promise语法,可以转成异步Promise返回:

// rxjs v7及以上版本需要导入firstValueFrom
import { firstValueFrom } from 'rxjs';

public async isLoggedIn(): Promise<boolean> {
  const url = `${this.endPoint}/me`;
  try {
    // rxjs v6及以下写await this.http.get<any>(url).toPromise()
    await firstValueFrom(this.http.get<any>(url));
    return true;
  } catch (err) {
    return false;
  }
}

调用示例:

// 调用的方法需要加async修饰
async checkLogin() {
  const isLogin = await this.isLoggedIn();
  console.log('是否登录:', isLogin);
}

// 或者用then回调
this.isLoggedIn().then(isLogin => {
  console.log('是否登录:', isLogin);
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 23:09:04