【问题标题】:function with get / http / subscribe dont worked, why? [duplicate]使用 get / http / subscribe 的功能不起作用,为什么? [复制]
【发布时间】:2020-05-11 00:03:22
【问题描述】:

这个带有get/http/subscribe的函数没有返回正确的值,它返回undefined,为什么?`

function_one() {
    let text = this.getData();
    console.log(' Here text is undefined --> ', text);
  }

  getData() {
    this.http.get("assets/img/tutorial/tutorialenus.JSON").subscribe
      (response => {
        console.log(' Here response = The simple text', response);
        return response;
      }
      );
  }

【问题讨论】:

  • getData() 中没有返回语句,您从订阅回调返回 response
  • 谢谢你们 - 我阅读了所有的帖子并为我工作

标签: json angular typescript ionic-framework


【解决方案1】:

没有看到其余的代码:我会推荐这个:

getData() {
  //return observable
  return this.http.get("assets/img/tutorial/tutorialenus.JSON");
}

function_one() {
  //subscribe to and log observable response data
  this.getData().subscribe
  (response => {
    console.log(' Here response = The simple text', response);
  }
}

【讨论】:

  • 没关系!工作...谢谢
【解决方案2】:

HTTP get 函数是异步的。所以它不会将数据返回给 function_one()。要解决这个问题,不要让 function_one() 调用 getData(),而是让 getData() 调用 function_one()。

像这样

  function_one(text) {        
    console.log(' Here text is undefined --> ', text);
  }

  getData() {
    this.http.get("assets/img/tutorial/tutorialenus.JSON").subscribe
      (response => {
        console.log(' Here response = The simple text', response);
        this.function_one(response)
      });
  }

【讨论】:

    【解决方案3】:

    您需要返回您的 observable 并订阅它才能获得价值。

    试试这个:

    function_one() {
        this.getData().subscribe((text) => {
            // Do something with text
            console.log('Your text will appear', text);
        });
    
    }
    
    getData() {
        return this.http.get("assets/img/tutorial/tutorialenus.JSON");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多