简体   繁体   中英

component.ts class gives an error when the return type is iActionResult

I am a bit confuse right now. Whenever i return void from my controller class everything works fine.

my controller.cs class.

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    [HttpPut("[action]")]
    public void EditEmployee(Employee employee)
    {
        if (ModelState.IsValid)
        {
            _repo.edit(employee);
            _repo.Save();
           // return Ok($"update was successful for {employee}");
        }   
      //  return BadRequest("Something Went Wrong");

    }

my service.ts class

 updateEmployee(employee) {
  let token = localStorage.getItem("jwt");
  return this._http.put('api/Employee/EditEmployee', employee, {
    headers: new HttpHeaders({
      "Authorization": "Bearer " + token,
      "Content-Type": "application/json"
  })
})

}

and my component.ts class

onSubmit(employeeForm: NgForm) {
//console.log(employeeForm.value);
this._employeeService.updateEmployee(employeeForm.value).subscribe(
  success => {
    this.Message = "Record Uploaded Successfully";
  },

  err => this.Message = "An error Occurred"
);

the code example above works as expected and returns Record Uploaded Successfully

but whenever i change the return type in my controller.cs class to IActionResult ,

   [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    [HttpPut("[action]")]
    public IActionResult EditEmployee(Employee employee)
    {
        if (ModelState.IsValid)
        {
            _repo.edit(employee);
            _repo.Save();
            return Ok($"update was successful for {employee}");
        }   
       return BadRequest("Something Went Wrong");
    }

it updates the record successfully in my database but returns An Error Occurred in my component.ts class

this is it on github

i want to understand what is happening and why i am experiencing this error.

Image when controller.cs file returns void

and

Image when controller.cs file returns IActionResult

Return a json object from your controller.cs class not a string literal

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[HttpPut("[action]")]
public IActionResult EditEmployee(Employee employee)
{
    if (ModelState.IsValid)
    {
        _repo.edit(employee);
        _repo.Save();
        return Json(new { Message="Update was successful!"});
    }   
   return BadRequest(new { Message="Something went wrong!"});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM