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

Angular4报错:类型‘Object’不存在属性‘json’

解决Angular 4中调用API时data.json()报错的问题

Hey there! Let's fix this issue you're running into with your Angular 4 app. This is a super common gotcha when working with Angular's newer HTTP tools, so let's break it down step by step.

问题根源

Starting in Angular 4, the HttpClient (from @angular/common/http) automatically parses JSON responses for you. That means when you subscribe to the observable returned by your API call, the data you get is already the parsed JSON object—you don't need to call .json() on it anymore. If you try to run .json() on this parsed data, you'll get an error because plain JavaScript objects don't have a .json() method.

修复步骤

  1. 修正组件中的订阅代码
    Remove the unnecessary .json() call and assign the data directly to your variable:

    ngOnInit(){ 
      this.CartdataService.get_Product_Categories().subscribe( 
        data => { 
          this.dropdownData = data; // 直接使用已解析的JSON数据
        } 
      ); 
    }
    
  2. 确保你的服务使用HttpClient
    Double-check your CartdataService to confirm it's using the modern HttpClient (not the old, deprecated Http):

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Observable } from 'rxjs';
    
    @Injectable()
    export class CartdataService {
      constructor(private http: HttpClient) {}
    
      get_Product_Categories(): Observable<any> {
        return this.http.get('你的API接口地址'); // get方法直接返回解析后的JSON数据流
      }
    }
    
  3. 在根模块中导入HttpClientModule
    Don't forget to add HttpClientModule to your AppModule's imports—this is required to use HttpClient anywhere in your app:

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { HttpClientModule } from '@angular/common/http';
    
    import { AppComponent } from './app.component';
    import { CartdataService } from './cartdata.service';
    
    @NgModule({
      declarations: [AppComponent],
      imports: [BrowserModule, HttpClientModule], // 添加入口模块
      providers: [CartdataService],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

如果你还在使用旧的Http(不推荐)

If for some reason you're stuck using the deprecated Http module (from @angular/http), then you would need the .json() call—but note that this module was removed in Angular 5. To make it work:

  • Import HttpModule in your AppModule
  • Inject Http instead of HttpClient in your service
  • Keep the .json() call in your component

But I strongly recommend switching to HttpClient—it's more efficient, supports type safety, and is the standard tool for Angular 4+.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:02:40