【问题标题】:TypeScript Global variables not changed in Observable subscribe methodObservable 订阅方法中的 TypeScript 全局变量未更改
【发布时间】:2017-10-08 20:38:23
【问题描述】:

我正在尝试使用 rxJS 来处理来自 angular2 中的 http 请求的响应

这是代码:

isUserConfirmed(): boolean {
    let result: boolean = false;
    this.authService.isUserConfirmed().subscribe(
      retrievedData => {
        //if no errors from the server
        if (retrievedData.success) {
          //if the confirmed flag is true
          if (retrievedData.payload){
            result = true;
            console.log("i"+result);
          } else {
            result = false;

          }
        } else {
          this.showError(retrievedData.message);
        }
      },
      error => {
        this.showError(error);
      });
      console.log("o"+result);
      return result;
  },

showError(error) {
  //...
}

编辑

当我运行它时,我得到这个输出:

ofalse
itrue

这意味着在 suscribe 方法中将结果值设置为 true,但这不会改变返回的结果值。
我怎样才能设法从订阅块中返回值集?

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:

    这是因为您在订阅块之外的控制台语句将首先执行。所以你的第一个 console.log() 将显示为 false。在订阅块内的console.log() 之后将第二次执行。所以如果成功就会返回true。

    如果 Observable 返回 true,则结果应该是:

    false
    true
    

    你可以这样返回值

    isUserConfirmed(): boolean {
        let result: boolean = false;
        return this.authService.isUserConfirmed().subscribe(
          retrievedData => {
            //if no errors from the server
            if (retrievedData.success) {
              //if the confirmed flag is true
              if (retrievedData.payload){
                result = true;
                console.log("i"+result);
              }
            } else {
              this.showError(retrievedData.message);
            }
            return result
          },
          error => {
            this.showError(error);
          });
      }
    

    【讨论】:

    • 您对日志顺序的看法是正确的,那么我怎样才能设法从订阅块返回结果值?
    • 我已经添加了代码,看看返回语句。 1. return this.authService.isUserConfirmed().subscribe() 2. return result 这可能会解决你的问题
    猜你喜欢
    • 2015-05-19
    • 1970-01-01
    • 2019-07-13
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多