Tan*_*wer 3 .net-core asp.net-core-webapi angular
我在.Net Core中有一个API,我在angular 5 app中使用它
以下是我的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);
}
}
Run Code Online (Sandbox Code Playgroud)
它确实返回一个字符串值,在swagger UI中检查
现在是Angular Code
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));
Run Code Online (Sandbox Code Playgroud)
}
在调用API之后,我在控制台中得到了输出
当我尝试将结果存储在会话中而不是它给出语法错误JSON.parse()中位置0的JSON中的意外的标记S
如何在角度使用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));
Run Code Online (Sandbox Code Playgroud)
使用旧版本的Angular时,您将使用Http类而不是HttpClient.使用Http类,json的自动解析没有完成.
| 归档时间: |
|
| 查看次数: |
1382 次 |
| 最近记录: |