Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning single string value from API in angular

I have an API in .Net Core and I am using it in angular 5 app

Below is My API

[Route("api/[controller]")]
public class CommonController : Controller
{
    private readonly IConfiguration configuration;
    private readonly CommonUtility util;

    public CommonController(IConfiguration _configuration)
    {
        configuration = _configuration;
        util = new CommonUtility(_configuration);
    }

    [HttpGet("[action]/{StaffCode}")]
    public string GetUserName(string StaffCode)
    {
        return util.GetName(StaffCode);
    }
}

it does return a string value , checked in swagger UI

Now Angular Code

GetUserName() {
this.http.get<string>(this.baseUrl + 'api/Common/GetUserName/' + this.StaffCode).subscribe(result => {
  sessionStorage.setItem("UserName", result);
  alert(sessionStorage.getItem("UserName"));
}, error => console.log(error));

}

Here after calling the API I m getting below output in console

enter image description here

When I try to store result in session than it give syntax error Unexpected token S in JSON at position 0 at JSON.parse ()

How to use output of API here in angular ?

like image 746
Tanwer Avatar asked Aug 08 '18 05:08

Tanwer


1 Answers

When using HttpClient your response will automaticaly be assumed to be a json format and before it gets to your subscribe HttpClient will call JSON.parse(). Unless you specificaly tell it its not a json. You can do this with {responseType: text'}.

GetUserName() {
this.http.get(this.baseUrl + 'api/Common/GetUserName/' + this.StaffCode, {responseType: text'}).subscribe(result => {
  sessionStorage.setItem("UserName", result);
  alert(sessionStorage.getItem("UserName"));
}, error => console.log(error));

When using older versions of Angular you would use the Http class instead of HttpClient. With the Http class this auto parsing from json was not done.

like image 103
Wannes Van Dorpe Avatar answered Nov 07 '22 15:11

Wannes Van Dorpe