簡體   English   中英

在 Angular 中解析來自 Http 請求的 json 響應

[英]Parsing json response from Http Request in Angular

我需要解析包含兩個鍵的 json 響應。 響應看起來像

{
status: 0;
message: 'some error 404'
}

在純 nodejs 或 React 中,您可以簡單地執行以下操作: if (response.status===1)console.log('success')

但是,我一直很難在角度上做到這一點。 有人可以指導我並告訴我如何解析 JSON 響應嗎? 我附上了代碼的模型。

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Component } from '@angular/core';

@Component({
    selector: 'app-create-employee',
    templateUrl: './create-employee.component.html',
    styleUrls: ['./create-employee.component.css']
})

export class CreateEmployeeComponent {
    
    constructor(private http: HttpClient) { };
    
    onFormSubmit() {
        let options = {
            headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
        };
        
        let body = new URLSearchParams();
        body.set('data', 'stackoverflow');
            

        this.http.post('http://localhost:8080/createEmployee', body.toString(), options)
        .subscribe(response => {
            console.log(response.status);
            console.log(response.message);
        });
    }
}

根據文檔,如果你告訴它如何做,Angular 可以從字符串響應中為你解析對象。 您可以以此為例。

首先在您的組件內部定義一個接口,就在您的導入下方:

  export interface Response {
    status: number,
    message: string
  }

這告訴 angular 如何解析來自服務器的 json 響應。 最后一點是在你的 post 請求中使用這個接口,如下所示:

this.http.post<Response>('http://localhost:8080/createEmployee', body.toString(), options)
        .subscribe(response => {
            console.log(response.status);
            console.log(response.message);
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM