首页 > 解决方案 > 在 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)
  }

问题是 -

  1. 我收到警报为 [object Object]
  2. console.log(this.session_otp) 给了我 {current_otp:"345262"} - 这意味着正在获取对象

如何从返回的对象中获取 OTP?(如在 console.log 中)我尝试了很多解决方案,其中大部分包括 JSON.stringify() 解决方案。没有工作。

请帮忙。

标签: c#angulartypescriptvisual-studioasp.net-web-api

解决方案


看起来您正在使用期望它成为其属性的对象。尝试这样的事情:

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属性而不是整个对象。


推荐阅读