我在.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中检查
现在 Angular 代码
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之后,我在控制台中获得以下输出
angular - 从API以 Angular 返回单个字符串值-LMLPHP
当我尝试将结果存储在 session 中时,它给出语法错误JSON.parse()中位置0的JSON中的意外 token S
如何在angular中使用API​​的输出?

最佳答案

使用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的自动解析。

关于angular - 从API以 Angular 返回单个字符串值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51739491/

10-10 00:42
查看更多