gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:31:27 25 4
gpt4 key购买 nike

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

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

在纯 Nodejs 或 React 中,您可以简单地执行以下操作:if (response.status===1)console.log('success')

但是,我在 Angular 中遇到了困难。有人可以指导我并告诉我如何解析 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);
});
}
}

最佳答案

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

首先在组件内定义一个接口(interface),位于导入下方:

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

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

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

关于json - 在 Angular 中解析来自 Http 请求的 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64966026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com