我创建产品的服务方法如下所示:
create(newProduct: Product): Promise<Product> {
return this.http
.post(this.productsUrl, JSON.stringify(newProduct), {headers: this.headers})
.toPromise()
.then(response => response.json() as Product)
.catch(this.handleError);
}
但现在服务器的JSON只有产品字段:
{
"id": 1,
"name": "Name"
}
现在我想从服务器发送一个包含产品和消息的json:
{
"product": {
"id": 1,
"name": "Name"
},
"message": "Operation was successful"
}
但我不知道如何从服务器检索服务中的对象和消息。
答案 0 :(得分:1)
您可以定义两个类,一个用于产品详细信息,另一个用于Post调用的响应。
export class Product{
id:string;
number:string;
}
export class PostResponse{
product:Product;
message:string;
}
现在,在你的电话会议中,你可以做'承诺&lt; PostResponse&gt;'而不是'承诺&lt;产品&gt;'检索响应对象。
答案 1 :(得分:0)
您可以观察map
运营商。
create(newProduct: Product): Promise<Product> {
return this.http
.post(this.productsUrl, JSON.stringify(newProduct), {headers: this.headers})
.map((res: Response) => {
let data= res.json();
return data.product;
})
.toPromise()
.then(response => response.json() as Product)
.catch(this.handleError);
}