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

Angular中Http Post返回Observable的subscribe回调未触发问题

问题原因排查
  • HttpHeaders 是不可变对象,调用append()方法后会返回新的Headers实例,当前写法没有接收返回值,实际发出的请求未携带Content-Type: application/json请求头。
  • 新版Angular HttpClient 已默认自动解析JSON格式的响应,手动调用response.json()会抛出异常,直接进入错误回调。
  • 若后端接口写入成功后返回204 No Content空响应,无任何JSON内容,此时尝试解析JSON也会触发异常,导致成功回调不执行。
  • 若存在跨域场景,后端虽然可处理请求,但返回的响应未携带合法的CORS头,浏览器会拦截响应内容,导致Observable进入错误回调。
修复方案

修正addUser方法代码

删除错误的Headers创建逻辑和多余的JSON解析逻辑,修正后代码如下:

addUser(user: User) : Observable<any> {
    // 构造函数内直接设置请求头,无需调用append
    const headers = new HttpHeaders({
        'Content-Type': 'application/json'
    });

    // 移除多余的map操作和response.json()调用
    return this.http.post('http://localhost:4000/api/users/add', user, {headers: headers});
}

补充错误日志排查(可选)

若修改后仍有问题,打印完整错误对象定位问题:

onSubmit(): void {
    this.userService.addUser(this.user)
        .subscribe(res => {
            console.log("Registration successful");
            this.isSuccessful = true;
        },
        err => {
            console.error("Registration failed: ", err); // 直接打印完整错误对象,不要字符串拼接
            this.isSignUpFailed = true;
        }
    );
}

适配后端空响应

若后端返回204无内容响应,指定响应类型为text即可:

return this.http.post('http://localhost:4000/api/users/add', user, {
  headers: headers,
  responseType: 'text'
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 17:45:02