简体   繁体   English

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

[英]Parsing json response from Http Request in Angular

I need to parse a json response containing two keys.我需要解析包含两个键的 json 响应。 The response looks like响应看起来像

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

In pure nodejs or React you could just simply do: if (response.status===1)console.log('success') .在纯 nodejs 或 React 中,您可以简单地执行以下操作: if (response.status===1)console.log('success')

However, I've been having a tough time doing this in angular.但是,我一直很难在角度上做到这一点。 Could someone guide me and tell me how could I parse the JSON Response?有人可以指导我并告诉我如何解析 JSON 响应吗? I have attached a mock-up of the code.我附上了代码的模型。

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);
        });
    }
}

According to the documentation , Angular can parse for you objects from string responses if you tell it how to do it.根据文档,如果你告诉它如何做,Angular 可以从字符串响应中为你解析对象。 You can use this as an example.您可以以此为例。

First define an interface inside your component just below your imports:首先在您的组件内部定义一个接口,就在您的导入下方:

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

This tells angular how to parse the json response from your server.这告诉 angular 如何解析来自服务器的 json 响应。 The final bit is to use this interface in your post request like this:最后一点是在你的 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