Get object that was created on the server via Angular

0

Good morning, people,

I'm new to Angular 4 (using TypesCript) and I'm having a basic question, but I did not find an answer here.

I have a typescript method that calls a method from a WebAPI. This WebAPI method creates an object and returns OK (objectCreate). I am not able to retrieve data from the object just created. I would like to give a console.log of the object I created, but the first time I save it, it gives undefined and the second time, it brings the previously created object and not the last one.

I know it's a tech bug, sorry.

Follow my code:

WebAPI Controller:

    [HttpPost]
    public Professor Create(Professor p)
    {
        //if (!ModelState.IsValid)
        //{
        //    BadRequest();
        //}
        IKernel ninjectKernel = new StandardKernel();
        ninjectKernel.Bind<IProfessorBLO>().To<ProfessorBLO>();
        IProfessorBLO blo = ninjectKernel.Get<IProfessorBLO>();

        blo.Add(p);

        //return Created(new Uri(Request.RequestUri + "/" + p.Id), p);
        return p;
    }

Method in TypeScript:

  submit(form){
    let professor = form.value.professor;
    let response = this.service.create(form.value.professor);
    console.log(response);
  }

this.service.create method:

  create(object){
    this.http.post(this.url,JSON.stringify(object), this.options)
    .subscribe(response=> {
      this.response = response;
    });
    return this.response.json();
  }
    
asked by anonymous 08.11.2017 / 15:00

1 answer

0

See that this.http.post is asynchronous, so this.response may not have the value returned by the server when the create function terminates. A possible solution would be to pass a callback function, to be executed when the response from the server reaches the client.

Method in TypeScript:

submit(form){
  let professor = form.value.professor;
  this.service.create(form.value.professor,
    response=> console.log(response));
}

Method this.service.create :

create(object, callback){
  this.http.post(this.url,JSON.stringify(object), this.options)
  .subscribe(response=> {
    this.response = response;
    callback(response);
  });
}
    
08.11.2017 / 16:07