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



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

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

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

您可以定义两个类,一个用于产品详细信息,一个用于 Post 呼叫的响应。

export class Product{
    id:string;
    number:string;
}
export class PostResponse{
    product:Product;
    message:string;
}

现在,在帖子调用中,您可以执行"承诺<后响应>"而不是"承诺<产品>"来检索响应对象。

你可以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);
    }

最新更新