【问题标题】:Angular 2 - GUI not update when change model in PromiseAngular 2 - 在 Promise 中更改模型时 GUI 不会更新
【发布时间】:2017-05-09 08:34:38
【问题描述】:

我编写了一个服务返回一个承诺,在组件中我调用服务并将模型设置为从承诺的成功函数返回的数据,模型已更改但 GUI 未更新。我该如何解决这个问题。

Service : 

getPage(pageNo) {
  return new Promise ((resolve, reject) {
    this.http.get(this.dataGetPageUrl+"/" + pageNo)
      .map(response => response.json())
      .subscribe(
        blocks => {
          resolve(blocks);
        },
        error => console.log(error)
      );
  })
}


Component: 

Service.getPage(1).then(function(data) {
  this.model = data;
}).catch(function(error) {

})

【问题讨论】:

    标签: angular service components


    【解决方案1】:

    因为function this. 没有指向当前类。改用()=>(箭头函数):

    Service.getPage(1).then((data) => {
      this.model = data;
    }).catch((error) => {
    

    【讨论】:

    • 我已经使用了你的代码,它显示了正确的数据长度结果,但没有使用 ngFor 呈现列表数据。
    • 控制台有错误吗? *ngFor 的代码是什么样子的?
    • 您不能在 cmets 中格式化代码。您可以用单个反引号 ` 包装,以确保将其呈现为代码。最好编辑问题并在那里添加代码。
    • 很难说为什么它没有被渲染。我认为这需要 Plunker 才能重现。
    • 对不起,这是我的错误,现在可以使用,非常感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 2021-05-21
    • 2020-03-03
    • 2017-09-07
    • 2016-10-15
    • 2020-05-18
    • 1970-01-01
    相关资源
    最近更新 更多