【发布时间】:2017-08-31 23:02:41
【问题描述】:
我尝试向其结构中包含另一个对象的对象的 API 发出发布请求,但出现错误。错误不清楚,但调试后得出的结论是请求中的json无效。
这是我的结构,我截断了 getter 和 setter 以保持代码最少:
export class Spot {
protected _id: number;
protected _name: string;
protected _address: string;
protected _city: City;
}
export class City {
protected _id: number;
protected _name: string;
}
这是我的服务:
import { Observable } from 'rxjs/Rx';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../../environments/environment.prod';
import { Injectable } from '@angular/core';
import { Spot } from './../../models/spot';
const spotUrl = environment.BASE_API_URL + 'blasti/spots';
@Injectable()
export class AdminSpotService {
private headers = new HttpHeaders({'Content-Type': 'application/json', 'Accept': 'application/json'});
constructor(private _http: HttpClient) { }
getAllSpots(): Observable<Spot[]> {
return this._http.get<Spot[]>(spotUrl);
}
createSpot(spot: Spot): Observable<Spot> {
console.log(spot);
return this._http.post<Spot>(spotUrl, spot, { headers: this.headers });
}
}
console.log(spot) 给出:
Spot {_name: "name", _address: "fefe", _city: "[object Object]"}
address
:
(...)
city
:
(...)
id
:
(...)
name
:
(...)
_address
:
"fefe"
_city
:
"[object Object]"
_name
:
"name"
API 收到 {_name: "name", _address: "fefe", _city: "[object Object]"} 无效,因为 _city 未通过 post 方法字符串化。
PS:我使用 HttpModule + JSON.stringify(spot) 得到了相同的结果。 HttpClientModule 可用于 Angular 4.3 及更高版本,它通常在不指定 JSON.stringify() 的情况下对对象进行字符串化。
我希望一些角度的专家有一个解决方案。
感谢您的宝贵时间。
【问题讨论】:
-
它在
console.log之前被字符串化了,你可以看到它显然是_city: "[object Object]"那里 -
_city 也必须被字符串化,我需要
_city:{"_name": "Paris", "_country": "France"}而不是 Object。 -
我的意思是在传递到这个 createPost 函数之前,对象的格式不好。
标签: json angular httpclient