Angular4报错:类型‘Object’不存在属性‘json’
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.
修复步骤
修正组件中的订阅代码
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数据 } ); }确保你的服务使用
HttpClient
Double-check yourCartdataServiceto confirm it's using the modernHttpClient(not the old, deprecatedHttp):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数据流 } }在根模块中导入
HttpClientModule
Don't forget to addHttpClientModuleto yourAppModule's imports—this is required to useHttpClientanywhere 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
HttpModulein yourAppModule - Inject
Httpinstead ofHttpClientin 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

