如何从带有消息的服务器对象接收

时间:2017-06-20 13:49:33

标签: javascript angular angular2-services

我创建产品的服务方法如下所示:

    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"
}

但我不知道如何从服务器检索服务中的对象和消息。

2 个答案:

答案 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);
    }