gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:06:33 25 4
gpt4 key购买 nike

我在 .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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com