【问题标题】:Assign a return value of promise to the variable always undefined ionic2将 promise 的返回值赋给变量 always undefined ionic2
【发布时间】:2017-12-29 10:46:21
【问题描述】:

我是 Ionic 世界的新手,当我在构造函数中调用函数时遇到了一些麻烦。 我正在制作一个为大学房间腾出空间的应用程序。我已经设置了我的 Web 服务并正在进行 HTTP 调用以获取答案,但在某些情况下,我需要保存这些返回的值,这样我就不必每次都重做 HTTP 调用。但是每次我尝试在承诺之外访问这些变量的值时,它们都会返回 undefined。

这就是我正在做的事情,我的问题是:如何在变量中分配承诺的返回值而不丢失它的上下文。

export class MainPage{
  rooms: Array<Sala>; //array of rooms

  constructor(public navCtrl: NavController, public navParams: NavParams, public connection: ConnectionService) {
    this.callLoadRoom();
  }

  callLoadRoom() {
    var that = this;
    this.connection.loadRoom()
      .then( (data: Array<Sala>) => {
        that.rooms = data;
      }, (error) => {
        console.log("Load Rooms Error!", error);
      });
  }

  printRooms(){
    console.log(this.rooms)
  }
} 

连接类是执行对 Web 服务的 HTTP 调用的提供程序。这是我的做法:

loadRoom() {
    return new Promise((resolve, reject) => {
      this.http.get(this.baseUri+'sala/carregarSala')
        .map(res => res.json())
        .subscribe(data => {
          resolve(data);
        },
        error => {
          reject(error);
        });
    });
  }

谢谢大家!

【问题讨论】:

  • 但每次我尝试在承诺之外访问这些变量的值时,它们都会返回 undefined。 你什么时候尝试访问它,我可以看到在哪里,但这是点击事件还是 printRooms() 何时被调用?
  • 假设 printRooms() 函数在 callLoadRoom() 函数之后调用,我需要在 ROOMS 向量中分配的值可用于执行其他操作。你能帮我解决这个问题吗?
  • 我可能会将此视为此的副本:stackoverflow.com/questions/43055706/… 这是异步性质,除了正确链接它之外,您无法确定该值是否存在。有一些 rxjs 函数可以帮助解决这个问题,但由于不知道确切的用例(何时/如何调用 printRooms())所以没有确切的用例,这是我能提供的最好的:)

标签: angular typescript ionic2


【解决方案1】:

不要用var that = this没必要,直接用this。

您的loadRoom() 方法可以像这样清理:

loadRoom() {
  return this.http.get(this.baseUri+'sala/carregarSala')
    .map(res => res.json())
    .toPromise()
    .catch(err => {
       // handle error here
    }
}

更多关于.toPromise()in this question的信息

你可以看到live plunker demo here

【讨论】:

  • 您需要在清理后的loadRoom()中返回承诺
  • 啊,是的,谢谢 - 我在 plunker 中修复了它,忘记更新答案了!
猜你喜欢
  • 1970-01-01
  • 2018-03-03
  • 1970-01-01
  • 2017-01-16
  • 2014-05-12
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 2020-11-28
相关资源
最近更新 更多