4

I could use some guidens, sending an object from my angular 2 application to the Web API.

I know how to GET objects from the Web Api, to my angular 2 application, but can't seem to figure out how the post method works or even if I should use the http.post methodd.

My angular 2 application has the following method:

sendUpdatdReservation(updatedReservation: Reservation) {

    var result;
    var objectToSend = JSON.stringify(updatedReservation);

    this.http.post('http://localhost:52262/api/postbookings', objectToSend)
    .map((res: Response) => res.json()).subscribe(res => result = res);

    console.log(result);

}

The "updatedReservation" is an object, which I convert to JSON.

The Web api can be reached by the following address:

httl://localhost:52262/api/postbookings

Web Api controller:

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class PostBookingsController : ApiController
{
    [AcceptVerbs()]
    public bool ConfirmBooking(Booking booking)
    {
        return true;
    }

}

What I'm trying to do is to send the object, update my database based on the changes values that the object has. Then send back true or false if this is a confirmation or not so I can redirect to confirmation page.

Do any know the unsupported media type error?, is that related to that the object i send is not what the api method expects?

Hope someone can help.

1

1 Answer 1

9

You need to set the Content-Type header when sending the request:

sendUpdatdReservation(updatedReservation: Reservation) {
  var result;
  var objectToSend = JSON.stringify(updatedReservation);

  var headers = new Headers();
  headers.append('Content-Type', 'application/json');

  this.http.post('http://localhost:52262/api/postbookings', objectToSend, { headers: headers })
     .map((res: Response) => res.json()).subscribe(res => {
       this.result = res;
       console.log(this.result);
     });
}

Don't forget to import this class:

import {Http,Headers} from 'angular2/http';
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your quick reply.. now i'm getting Access-Control-Allow-Origin error, which I should not, cause I have cors enabled. NVm.. its working now :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.