Angular 2中的HTTP请求方法
问题描述:
我有一个提交食物模型数据的表单。当SubmitFood函数被触发时,表单提交数据。 SubmitFood函数将模型ie.this.httpService.addFood(this.model)提交到后端工作正常。 但这是我目前想要做的。 表单提交的模型属于特定的食物类型。所以SubmitFunction应该沿着food_id参数(从url中捕获的id)提交。 服务addFood也等待一个id(food.id),所以它可以将它绑定到url。所以在这种情况下,当我提交表单的url应该是“http://localhost:8000/api/foods/v1/type/100/location”。即,SubmitFood功能将向服务发送id = 100,以知道要发送的模型属于哪种食物类型。Angular 2中的HTTP请求方法
addFood(food:any){
const body = JSON.stringify(food);
const headers = new Headers();
return this.http.post('http://localhost:8000/api/foods/v1/type/'+food.id+'/location', body, {headers: headers})
.map((data:Response) => data.json());
}
//component
export class FoodComponent implements OnInit{
private food_id;
constructor(private httpService: HttpService , private route:ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe(params => {if (params['id']) {
this.food_id = params['id'];
}
})
}
model = {
type:"",
location:""
};
SubmitFood(){
this.httpService.addFood(this.model)
.subscribe(data => {
console.log(data);
})
}
答
你只需要food_id传递给服务:
SubmitFood(){
this.httpService.addFood(this.food_id)
.subscribe(data => {
console.log(data);
})
}
餐饮服务:
addFood(foodId: number){
const body = JSON.stringify(food);
const headers = new Headers();
return this.http.post('http://localhost:8000/api/foods/v1/type/'+foodId+'/location', body, {headers: headers})
.map((data:Response) => data.json());
}
+0
非常感谢!!!!! –
问题是什么/问题? –
@IgorJanković我怎么能发送food_id参数到服务addFood –