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

Angular中'then is not a function'报错原因及解决方法求助

解决TypeScript中调用get_data()时出现'then is not a function'的问题

我来帮你分析这个问题哈,其实这个错误的原因很明确,咱们一步步拆解:

错误原因

  • 你的get_data()方法返回的是Subscription对象:你在Observable链的末尾调用了subscribe(),而subscribe()的返回值是用于取消订阅的Subscription实例,它并没有then()方法。
  • then()是Promise对象专属的方法,只有Promise才能调用它,你现在拿到的是Subscription,自然会抛出'then is not a function'的错误。

解决方法

这里给你两种常见的解决方案,你可以根据自己的习惯选择:

方案一:返回Observable,在调用处订阅(Angular推荐用法)

修改get_data(),去掉内部的subscribe(),只返回Observable流:

get_data(){ 
  return this.http.get('assets/data/user.json').map(res => res.json()); 
}

然后在helloworld()里通过subscribe()获取数据并赋值:

helloworld(){ 
  this.get_data().subscribe(data => { 
    console.log(data); 
    this.json_data = data; // 在这里完成数据赋值
  }); 
}

这种方式是RxJS的标准用法,能充分利用Observable的数据流特性,比如后续可以轻松添加取消订阅、数据转换等操作,非常适合Angular项目。

方案二:将Observable转为Promise,继续使用then()

如果你更习惯Promise的语法,可以把Observable转换成Promise,用toPromise()方法:

get_data(){ 
  return this.http.get('assets/data/user.json').map(res => res.json()).toPromise(); 
}

这样get_data()返回的就是Promise对象了,原来的helloworld()代码不需要修改就能正常运行:

helloworld(){ 
  this.get_data().then(data => { 
    console.log(data); 
    this.json_data = data; 
  }); 
}

额外小提示(针对Angular 4.3+)

如果你用的是Angular 4.3及以上版本的HttpClient,它的get()方法会自动解析JSON响应,不需要手动调用res.json(),代码可以简化成:

// 简化后的get_data
get_data(){ 
  return this.http.get<any>('assets/data/user.json'); 
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:22:32