在延迟值之后,Angular 4视图不会更新

时间:2017-09-13 12:53:01

标签: angular ionic2

我从离子存储器获取一些数据,并希望在视图中显示。问题是我从存储中获取对象,将它们推入数组,并希望在视图中显示它们,但由于存储延迟1秒,视图不显示值。

这里我得到了对象并推入了数组:

this.tickets$.subscribe(tickets => {
      this.tickets = tickets.toList()
      this.tickets.forEach(ticket =>{
        let bonusStakeStr = "bonusStake-"+ticket.ticketId;
        this.storage.get(bonusStakeStr).then(response=> {
           this.ticketStakes = [];
            if (response) {
              let obj =  {};
              obj[ticket.ticketId] = response ;
              this.ticketStakes.push(obj);
            }
          }
        )

      });

这是阵列的吸气剂:

getTicketStakesFromStorage(){
   return this.ticketStakes;
  }

这是我视图的控制器,我在构造函数中设置了数组:

this.ticketStakes = this.bonusService.getTicketStakesFromStorage();

获取视图的数组值:

getBonusOdd(ticketId){
    if(this.ticketStakes.length<=0)console.log("array is empty")
    if(this.ticketStakes.length>0)console.log("array is not empty")
    this.ticketStakes.forEach(ticketStake => {
      if(ticketStake.hasOwnProperty(ticketId)){
        let odd =  this.myCurrency(ticketStake[ticketId]);
        console.log(odd)
        return odd;
      }
    })
  }

在这样的观点中:

<ion-col width-50 left>{{getBonusOdd(ticket.ticketId)}}</ion-col>

首先是"if(this.ticketStakes.length<=0)console.log("array is empty")"部分 打印出来然后"if(this.ticketStakes.length>0)console.log("array is not empty")"打印出..所以我假设有1秒的延迟,但视图不识别.. 任何想法都会受到很大关注!

1 个答案:

答案 0 :(得分:0)

更新视图的一种方法(还有其他特定于您实现的逻辑方法)是使用detectChanges()类的ChangeDetectorRef方法。它是从@angular/core这样导入的,

import { ChangeDetectorRef } from '@angular/core';

在构造函数中将其作为参数注入,如下所示,

constructor (private ref: ChangeDetectorRef) {}

然后在getBonusOdd()方法内部使用它,

getBonusOdd(ticketId){
 if(this.ticketStakes.length<=0)console.log("array is empty")
 if(this.ticketStakes.length>0) {
  console.log("array is not empty");
  this.ticketStakes.forEach(ticketStake => {
   if(ticketStake.hasOwnProperty(ticketId)){
     let odd =  this.myCurrency(ticketStake[ticketId]);
     console.log(odd);
     return odd;
   }
  });
  this.ref.detectChanges();
 }
}