Angular 2中的HTTP请求方法

时间:2017-02-27 08:28:55

标签: angular

我有一份提交食物模型数据的表格。表单在触发SubmitFood函数时提交数据。 SubmitFood函数将模型ie.this.httpService.addFood(this.model)提交给后端工作正常。 但这就是我目前要做的事情。 表格提交的模型属于特定的食物类型。所以SubmitFunction应该沿着food_id参数提交(从网址捕获的id)。 服务addFood也等待id(food.id),因此它可以将它绑定到url。因此,在这种情况下,当我提交表单时,网址应该像" http://localhost:8000/api/foods/v1/type/100/location"。即SubmitFood函数将向服务发送id = 100以知道正在发送的模型属于哪种特定食物类型。

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

1 个答案:

答案 0 :(得分:2)

您只需要将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());

}