如何从服务器对象接收消息
How to receive from server object with message
我创建产品的服务方法如下所示:
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;
}
现在,在您的 post 调用中,您可以 'Promise< PostResponse >' 而不是 'Promise< Product >' 来检索响应对象。
您可以观察到 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);
}
我创建产品的服务方法如下所示:
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;
}
现在,在您的 post 调用中,您可以 'Promise< PostResponse >' 而不是 'Promise< Product >' 来检索响应对象。
您可以观察到 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);
}