在Angular 7中,可以使用JSON.stringify()
方法将JSON对象转换为字符串,并在http.post请求中发送。
以下是一个示例代码:
import { HttpClient, HttpHeaders } from '@angular/common/http';
// ...
constructor(private http: HttpClient) {}
sendPostRequest(): void {
const url = 'https://example.com/api/post';
const data = {
id: 1234,
name: 'John Doe',
age: 25
};
const headers = new HttpHeaders({
'Content-Type': 'application/json'
});
const options = { headers: headers };
// 将数字作为字符串发送
data.age = data.age.toString();
this.http.post(url, JSON.stringify(data), options)
.subscribe(
response => {
console.log(response);
},
error => {
console.log(error);
}
);
}
在上面的代码中,首先创建了一个包含数字的JSON对象。然后,创建了一个HttpHeaders实例,并设置Content-Type为application/json。然后,使用JSON.stringify()方法将JSON对象转换为字符串,并将数字作为字符串发送。最后,通过http.post方法发送POST请求,并在订阅中处理响应和错误。