【问题标题】:View not updating after http call in Angular2 / Ionic2在 Angular2 / Ionic2 中的 http 调用后视图不更新
【发布时间】:2016-04-26 10:55:17
【问题描述】:

我有一个简单的 Ionic2 页面,需要从服务器获取数据并将其显示在模板中。

当我运行应用程序时,我会在控制台中看到所有从 console.log(res.Data); 获取的数据。

很遗憾,视图没有更新。但是,当我按下按钮时,一切都像魅力一样。

我还必须从ngOnInit 方法调用this.update(),但没有成功。有什么想法我在这里做错了吗?

代码

constructor(private timeline: TimelineService) {
    this.update();
}

update() {

  this.timeline.getTimeline(1).subscribe(res => {
    console.log(res.Data);
    this.timelineData = res.Data;
  });

}

模板

<pre>
    {{ timelineData?.length }}
</pre>

<button (click)="update()">Update</button>

<div *ngFor="#timelineItem of timelineData; #i = index">
    <timeline-item [data]="timelineItem"></timeline-item>
</div>

【问题讨论】:

  • 您是否尝试过从ngOnInit 生命周期挂钩调用更新函数.. 就像ngOnInit(){ this.update(); } 一样?
  • 这可能只是您的时间线项目组件的问题。如果您只是在 ngFor 中执行 {{ timelineItem }} 而不是调用该组件会怎样
  • 看起来确实与时间线项目组件有关。要去剥这个,看看有什么问题。谢谢!

标签: angular ionic2


【解决方案1】:

我发现您的模板有问题。由于您的数据是异步加载的,因此在尝试显示其length 属性时应该会遇到问题。

您可以在此级别尝试使用 Elvis 运算符:

<pre>
  {{ timelineData?.length }}
</pre>

【讨论】:

  • 感谢您的建议!不幸的是,这并没有解决我的问题。
  • 您能提供您定义组件的方式吗?我的意思是你在@Component...
  • 这不是来自 Ionic2 的 Component 而是 Page。也许我需要把所有东西都放在一个组件中。等一下:)
  • 这也应该在页面中工作 ;-) 让我试一试...也就是说,我将利用 onPageWillEnter 挂钩将您的数据加载到 Ionic2 页面中;-)跨度>
  • 看起来它在组件中有效,但在页面中无效。奇怪 :) 仍然想知道为什么你会选择 onPageWillEnter 而不是 onInit :)
【解决方案2】:

我有类似的工作,在 onPageLoaded() 下调用服务就像一个魅力。你试过了吗?

constructor(private timeline: TimelineService) {
}
onPageLoaded(){
 this.update();
}
update() {
  this.timeline.getTimeline(1).subscribe(res => {
    console.log(res.Data);
    this.timelineData = res.Data;
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 2016-04-02
    • 2017-08-28
    • 1970-01-01
    • 2017-05-23
    • 2017-12-19
    相关资源
    最近更新 更多