c# - 在 Typescript(Angular 8)中调用 subscribe() 时无法访问返回的对象的值
问题描述
这是我在 Visual Studio (Web API) 中生成 6 位 OTP 的地方
static int otp;
[HttpPost]
public void Post([FromBody] PhoneNum ph)
{
try
{
int otpValue = new Random().Next(100000, 999999);
otp = otpValue;
...
我正在使用 IHttpActionResult 返回 OTP 类对象
[Route("getotpsession")]
public IHttpActionResult GetOTPSession()
{
OTPClass otp_curr = new OTPClass();
otp_curr.current_otp = otp.ToString();
return Ok(otp_curr);
}
在 Angular 中,我尝试使用 subscribe() 获取此对象
getSessionOTP(){
this.session_otp = this.otpservice.getOTP().subscribe((data)=> {this.session_otp = data; console.log(this.session_otp)})
alert(this.session_otp)
}
问题是 -
- 我收到警报为 [object Object]
- console.log(this.session_otp) 给了我 {current_otp:"345262"} - 这意味着正在获取对象
如何从返回的对象中获取 OTP?(如在 console.log 中)我尝试了很多解决方案,其中大部分包括 JSON.stringify() 解决方案。没有工作。
请帮忙。
解决方案
看起来您正在使用期望它成为其属性的对象。尝试这样的事情:
getSessionOTP(){
this.session_otp = this.otpservice.getOTP().subscribe((data)=> {
this.session_otp = data.current_otp; console.log(this.session_otp)
alert(this.session_otp)
})
}
请注意,我现在使用的是current_otp
属性而不是整个对象。
推荐阅读
- python-3.x - 切换音乐开/关 Kivy
- c++ - 检查 nullptr 导致 CTD
- java - UnsatisfiedDependencyException java.lang.IllegalArgumentException:查询方法公共抽象 java.util.Optional 的验证失败
- azure - 如何为 Azure Log Analytics 启用自定义日志?
- python - 如何将从日期中提取的小时转换为小时+(以小时为单位的日期)?
- powerbi - Power BI 传递参数以报告
- shell - 根据 shell 脚本中的列值创建文件
- python - 如何在 Windows 10 上安装飞溅?我需要它来scrapy
- azure - 在 Azure WebJob 中引用 NuGet 包 MailKit
- python - 无法在 Python 中使用散点图正确绘制回归线