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
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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With