2

Trying to pass a payload via Typescript service to an http.post

My .ts code:

saveEdits(body: Object): Observable<Animal[]> {
    let bodyString = JSON.stringify(body); 
    let headers = new Headers({ 'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ headers: headers }); 

    return this.http.post(this.UrlToEdit, body, options)
        .map((res: Response) => res.json())
        .catch((error: any) => console.log("Edited value did not been saved"));
}

Mention that

private UrlToEdit = '/Home/Edit';

Although the value is up to the service, C# controller not seems to fire up.. An here its code:

[HttpPost]
public  async Task<Boolean> Edit([Bind(Include = "animalID,animalName,animalHabitat,animalClass")] Animal animal)
{
   if (ModelState.IsValid)
   {
      db.Entry(animal).State = EntityState.Modified;
      await db.SaveChangesAsync();
      return true;
   }
   return false;
}
croxy
  • 4,082
  • 9
  • 28
  • 46
Georgios
  • 1,454
  • 6
  • 17
  • 34
  • Could you ensure data presents in Fiddler? Could you show payload inside Fiddler and **Animal** class? – Win Oct 14 '16 at 15:01
  • Data do present to the Fiddler. Although, class is `export class Animal { animalID: number; animalName: string; animalHabitat: string; animalClass: string; }` – Georgios Oct 14 '16 at 15:04
  • Could you replace `[Bind(Include = "animalID,...,animalClass")]` with `[FromBody]`, and try again? – Win Oct 14 '16 at 15:05
  • Confused about the [FromBody] – Georgios Oct 14 '16 at 15:09

1 Answers1

2

I dont know how your whole site is working but maybe this helps you:

First i see an error in your code, you should pass the bodyString in the post not the body

return this.http.post(this.UrlToEdit, bodyString, options)
    .map((res: Response) => res.json())
    .catch((error: any) => console.log("Edited value did not been saved"));

Second post returns an Observable so the post is executed when something subscribes to the observable like this

//...somewhere in your code ...
service.saveEdits(body).subscribe((animals: Animal[]) => console.log(animals));

Also open chrome debugger (or whatever browser you use) and see in the network tab if the post is executed and if there is any error

I hope this helps you

buluba89
  • 776
  • 8
  • 6
  • This is actually the answer(very very similar) http://stackoverflow.com/questions/36208732/angular-2-http-post-is-not-sending-the-request Thank you for taking the time! – Georgios Oct 14 '16 at 16:03