angular - 以 Angular 从 API 返回单个字符串值

标签 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 中检查

现在是 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 之后,我在控制台中得到以下输出

enter image description here

当我尝试将结果存储在 session 中时,它给出了语法错误 Unexpected token S in JSON at position 0 at JSON.parse ()

如何在此处以 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 - 以 Angular 从 API 返回单个字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51739491/

相关文章:

javascript - 为什么我的组件的 html 在成功路由到它后不显示?

c# - 对 LockBits、BitmapData 和 PixelFormat.Format48bppRgb 感到困惑

c# - 调用 SignalR Hub 不适用于 Asp.Net Core Web API

node.js - Google OAuth2 : Redirect has been blocked by CORS policy: Request requires preflight, 不允许跟随跨域重定向

javascript - Angular 6 树可摇动提供程序和惰性模块

java - 为什么将 "/"附加到 base-href 就不需要部署 url?

c# - 无法在 Linux 机器上为使用 MySQL db 和 Pomelo.EntityFrameworkCore.MySql 的 dot net core 2.1 应用程序运行 docker 镜像

asp.net - 如何在Visual Studio(sln)解决方案中创建.env文件

c# - 如何像 JSON.stringify() 那样在 C# 中对 json 进行字符串化/规范化

c# - 在达到流畅的验证实现 C# 之前,如何避免 MVC 验证引发的错误