【问题标题】:Cannot access value of the object returned when subscribe() is called in Typescript (Angular 8)在 Typescript(Angular 8)中调用 subscribe() 时无法访问返回的对象的值
【发布时间】:2021-03-16 13:21:13
【问题描述】:

这是我在 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# angular typescript visual-studio asp.net-web-api


【解决方案1】:

这里的session_otp是一个对象,你需要从对象中访问current_otp属性。

但在您的代码中,alert 超出订阅范围。

试试这个代码,

getSessionOTP(){
    this.session_subscription = 
    this.otpservice.getOTP()
      .subscribe((data)=> {
          this.session_otp = data;
          console.log(this.session_otp);
          alert(this.session_otp.current_otp);
       });
 }

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我得到“属性 'current_otp' 在类型 'Object' 上不存在”作为错误,因为 current_otp 存在于 Visual Studio 的 OTPClass.cs 中。
    • 然后尝试data['current_otp'],即使没有输入,您也可以访问该属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 2013-10-10
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多