在 Angular 中解析来自 Http 请求的 json 响应

Cat*_*yst 2 json angular

我需要解析包含两个键的 json 响应。响应看起来像

{
status: 0;
message: 'some error 404'
}
Run Code Online (Sandbox Code Playgroud)

在纯 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);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

根据文档,如果您告诉 Angular 如何执行此操作,Angular 可以从字符串响应中解析对象。您可以以此为例。

首先在组件内定义一个接口,就在导入的下方:

  export interface Response {
    status: number,
    message: string
  }
Run Code Online (Sandbox Code Playgroud)

这告诉 Angular 如何解析来自服务器的 json 响应。最后一点是在您的发布请求中使用此接口,如下所示:

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