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

Angular6 HttpClient无法直接获取JSON对象,需JSON.parse的问题求助

Fixing Angular HttpClient Not Automatically Parsing JSON Responses

Hey there, let’s figure out why you’re stuck using JSON.parse() with Angular’s HttpClient—this shouldn’t be necessary at all, since HttpClient automatically parses JSON responses by default! Let’s break down the issue and fix it properly.

Why This Is Happening

By default, HttpClient.get() will auto-convert responses with a Content-Type: application/json header into JavaScript objects. If you’re seeing a raw string instead of a parsed object, one of two things is almost certainly going on:

  • Your backend API is returning a stringified JSON string (e.g., sending "{"companyName":"Apple"}" instead of the native JSON {"companyName":"Apple"}).
  • Your backend is setting the wrong Content-Type header (like text/plain instead of application/json), so HttpClient doesn’t recognize it as JSON to parse.

Step 1: Verify Your Backend Response

First, check your API’s response using your browser’s dev tools (Network tab):

  1. Look at the Content-Type header in the response—it should be application/json.
  2. Inspect the response body: it should be a plain JSON object, not a quoted string wrapped in quotes.

Step 2: Fix the Issue (Frontend or Backend)

The best long-term fix is to adjust your backend to:

  • Set the Content-Type: application/json header on all JSON responses.
  • Return a native JSON object directly, not a stringified version of JSON.

Once you do this, your original component code will work perfectly without JSON.parse()—you’ll be able to access basic.companyName directly.

Option 2: Adjust Frontend Code (If Backend Can’t Be Changed)

If you can’t modify the backend, you can explicitly handle the string response in your service:

Update Your Service (dash-board-service.service.ts)

import { PhoneBasicInfo } from './../Models/PhoneBasicInfo';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators'; // Add this import

@Injectable({
  providedIn: "root"
})
export class DashBoardServiceService {
  private url = "http://localhost:57302/api/Phone";
  constructor(private http:HttpClient) { }
  
  getPhoneBasicInfo(): Observable<PhoneBasicInfo>{
    // Explicitly request text response, then parse it to JSON
    return this.http.get<string>(this.url, { responseType: 'text' })
      .pipe(
        map(response => JSON.parse(response) as PhoneBasicInfo)
      );
  }
}

Update Your Component (dash-board.component.ts)

Now you can remove the JSON.parse() call and access properties directly:

ngOnInit() {
  this.service.getPhoneBasicInfo()
    .subscribe( basic => {
      console.log(basic.companyName); // This will work now!
      // No need for JSON.parse(basic) anymore
    } );
}

Bonus: Ensure Type Safety

Since you’re using the PhoneBasicInfo model, double-check that your backend response matches the structure of this class exactly. This will make sure TypeScript’s type checking works as intended, catching mismatches early.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:49:41