我在 .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 之后,我在控制台中得到以下输出
当我尝试将结果存储在 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/