user
user

Reputation: 4840

How to receive from server object with message

My service method for creating products looks like below:

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

but now JSON from server has only fields of product:

{
   "id": 1,
   "name": "Name"
}

And now I want to send from server a json which will contain a product and message:

{
   "product": {
      "id": 1,
      "name": "Name"
   },
   "message": "Operation was successful"
}

But I don't know how to retrieve object and message in service from server.

Upvotes: 0

Views: 44

Answers (2)

CharanRoot
CharanRoot

Reputation: 6325

you can observable map operator.

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

Upvotes: 0

SubbU
SubbU

Reputation: 359

You can define two classes, one for product details and one for the Post call's response.

export class Product{
    id:string;
    number:string;
}

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

Now, in your post call, you can do 'Promise< PostResponse >' instead of 'Promise< Product >' to retrieve the response object.

Upvotes: 1

Related Questions