从API以角度返回单个字符串值

时间:2018-08-08 05:56:50

标签: angular .net-core asp.net-core-webapi

我在.Net Core中有一个API,并且在angular 5应用程序中使用了它

下面是我的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);
    }
}

它确实返回了一个字符串值,已在swagger UI中进行了检查

现在的角度代码

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));

}

在调用API之后,我进入了控制台的输出

enter image description here

当我尝试将结果存储到会话中时,它给语法错误JSON.parse()中位置0的JSON中的意外令牌S

如何在此处以角度使用API​​输出?

1 个答案:

答案 0 :(得分:6)

使用HttpClient时,您的响应将自动假定为json格式,并且在到达您的订阅之前,HttpClient将调用JSON.parse()。除非您明确地告诉它它不是json。您可以使用{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));

在使用较旧版本的Angular时,您将使用Http类而不是HttpClient。使用Http类时,无法完成从json的自动解析。