Liska Liskor Liska Liskor -4 years ago 126
AngularJS Question

HTTP Request Method in Angular 2

I have a form for submitting data for food model. The form submits data when the SubmitFood function is triggered. The SubmitFood function submits the model ie.this.httpService.addFood(this.model) to the backend which works fine.
But this what i am trying to do currently.
The model being submitted by the form belongs to a specific food type. So the SubmitFunction should submit along the food_id param (the id being captured from the url).
The service addFood also awaits an id (food.id) so it can bind it to the url. So in that case, when i submit the form the url should be like "http://localhost:8000/api/foods/v1/type/100/location". i.e. The SubmitFood function will send an id = 100 to the service to know which particular food type the model being sent belongs to.

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

Answer Source

You just need to pass food_id to the service:

SubmitFood(){

    this.httpService.addFood(this.food_id)
        .subscribe(data => {

            console.log(data);
        })
}

Food Service:

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

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download