我嘗試發送一個包含另一個對象在他的結構中的對象的API的請求,但我有一個錯誤。錯誤不是很清楚,但經過調試後,我得出結論,請求中的json無效。Angular4 HttpClient stringify包含其他對象的對象
這裏是我的結構,我截斷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 {_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]"}
這是因爲,不被交方法stringifyed _City的無效。
PS:我有與HttpModule + JSON.stringify(點)相同的結果。 HttpClientModule可用於Angular 4.3及更高版本,它通常在不指定JSON.stringify()的情況下對對象進行字符串化。
我希望一些角度的專家有一個解決方案。
謝謝你的時間。
這是'console.log'之前字符串化,你可以看到它明顯是'_City:「的翻譯:」'有 –
_City也可這麼字符串化,我需要'_City: {「_name」:「Paris」,「_country」:「France」}'而不是Object。 – Zak
我的意思是在進入這個createPost函數之前,對象是壞的形式。 –