【问题标题】:Angular 8 Http Post get boolean value from subscribeAngular 8 Http Post 从订阅中获取布尔值
【发布时间】:2020-12-13 10:14:36
【问题描述】:

我试图从 subscribe 的布尔值 true/false 中获取价值,但我无法获取价值,这是我目前使用的。

我的 http post 的旧方法。

this.http.post(HostedPathConst.HostedPath + `CompanyProfile/UpdateCustomersStatus`, fData)
.subscribe(data => this.Success(data), err => this.Error(err)); 

this.Success(data)this.Error(err) 是现在调用的方法,我尝试获取数据的新方法是这样。

const fData = new FormData();
fData.append('Id', Id.toString());    
fData.append('IsActive', IsActive.toString());
const test = this.http.post(HostedPathConst.HostedPath + `CompanyProfile/UpdateCustomersStatus`, fData)
  .subscribe(data => {
    this.Success(data);
    this.Switch = IsActive;
    return this.Switch;
  },
    err => {
      this.Error(err);
      this.Switch = !IsActive;
      return this.Switch;
    });
    console.log(test);//Subscriber {closed: false, _parentOrParents: null, _subscriptions: Array(1), syncErrorValue: null, syncErrorThrown: false, …}
    console.log(this.Switch);//undefined at first then gives opposite result like true gives false and vice versa

作为 this.Switch = IsActive; 获取数据的布尔值,它首先返回 undefined,然后返回值 false 而不是 true反之亦然。

【问题讨论】:

  • 我并没有真正理解这里的问题,所以我知道您正在发布帖子的服务器的响应返回一个布尔值,但这意味着它可以正常工作并且您可以获得响应来自服务器。
  • @Erik 我的布尔值是一个复选框,如果选中它会返回 true,否则返回 false,但在第一种情况下,如果我在 console.log 上选中它的 false 并取消选中它的 true,它会返回 undefined 然后相反的值
  • 嗯,有一件事是肯定的。 Http 操作是异步的,所以在执行时有可能,这个 console.log(this.Switch);会在这之前发生,this.Switch = IsActive;所以也许,这就是你变得不确定的原因。
  • @Erik 我如何使用同步的例子会有帮助..?

标签: angular typescript angular8 angular-http


【解决方案1】:

因为我理解你的问题是因为异步的东西,所以我要在这里写一个解释。简单来说,您不知道异步操作何时结束。例如,当您执行 http 功能时,您正在与服务器通信,因此您不知道服务器何时会响应(因为连接速度慢,流量大,或者可能是因为您要求操作繁重)。

为了解决这个问题,我们使用了使用观察者模式的 subscribe() 方法。因此,这里的重点是因为您不知道服务器或操作(如线程)何时完成订阅并继续关注任何更改或答案。当你收到它时,订阅里面的代码就会执行。

您可以在此处了解有关观察者模式的更多信息:https://en.wikipedia.org/wiki/Observer_pattern#:~:text=The%20observer%20pattern%20is%20a,calling%20one%20of%20their%20methods。 和这里的异步理论:https://en.wikipedia.org/wiki/Asynchrony_(computer_programming)

对于您的问题,您可以将值初始化为 false,并将复选框值设置为 [(ngModel)]="Switch",这样当 switch var 更新时,复选框也会更新!

【讨论】:

    【解决方案2】:

    由于它是一个可观察的,您不会立即得到响应。所以控制台在成功和错误块内记录 this.Switch 。试试下面的sn-p

    const fData = new FormData();
    fData.append('Id', Id.toString());    
    fData.append('IsActive', IsActive.toString());
    const test = this.http.post(HostedPathConst.HostedPath + `CompanyProfile/UpdateCustomersStatus`, fData)
      .subscribe(data => {
        this.Success(data);
        this.Switch = IsActive;
        console.log("Success", this.Switch);
        return this.Switch;
      },
        err => {
          this.Error(err);
          this.Switch = !IsActive;
          console.log("Error", this.Switch);
          return this.Switch;
        });
    

    我不确定这是否会解决您的问题,但肯定会有助于调试以获得您的解决方案。

    注意:你得到undefined at first then gives opposite result like true gives false and vice versa的原因是你在成功或错误块之外安慰this.Switch,这将主要返回未定义的第一个和任何预分配的值。由于 this.Switch 是全局范围变量。

    【讨论】:

    • 当我使用 console.log(test) 进行测试时;//Subscriber {closed: false, _parentOrParents: null, _subscriptions: Array(1), syncErrorValue: null, syncErrorThrown: false, ...} 控制台。日志(this.Switch); // 一开始给出未定义的
    • 如何从“return this.switch”的订阅中获取返回值 boolean True/False.. ?
    • 我只想从布尔 True 或 False 中的订阅中获取值..
    • 抱歉,我想您还没有调试我上面提供的 sn-p。请参阅而不是将this.Switch 的值返回到变量test 为什么不能直接使用this.Switch 的值,因为它是一个全局范围。但是由于某种原因,您仍然需要将subscription value 分配给test,然后请参考此链接stackoverflow.com/questions/59448263/async-pipe-with-rxjs?rq=1 **注意:** 分配给test 的值仍然是Subscription<Boolean> 类型但不是Boolean
    • 在下面回答了我自己的问题并得到了预期的结果。
    【解决方案3】:

    使用asyncawait 获得结果,并且成功了。

    const test = await this.http.post(HostedPathConst.HostedPath + `CompanyProfile/UpdateCustomersStatus`, fData)
                     .toPromise().then((data)=>{
                      this.Switch = IsActive;
                      return this.Switch;
                     }).catch((error)=>{
                      this.Switch = !IsActive;
                      return this.Switch;
                     });
        console.log(test); //Same result as below
        console.log(this.Switch); //Same result as above
    

    【讨论】:

    • 您正在将一个可观察对象转换为一个承诺,它不会多次向test 发出事件,如果这对您有用,那就太酷了。无论如何,toPromise() 已被弃用,因此最好检查链接以获取备用 stackoverflow.com/questions/51677405/…
    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 2019-03-06
    • 2021-01-03
    • 2020-04-19
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多