繁体   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