在页面构造函数中调用函数会导致空数组

时间:2017-04-14 16:34:50

标签: javascript angular typescript ionic-framework ionic2

我尝试加载并绑定this.studentNames[i].checked以准备复选框(如果设置了复选框,则为localstorage中的键值对)。但是,正确地从this.studentNames数组中的存储中推送条目后(我可以在视图中的存储中看到所有这些条目),然后this.studentNames数组在数组中为空[]可以更长时间访问模型。

我是否以错误的方式使用此功能?我想,当我使用=>函数时,一切都应该没问题?!

我的观点(HTML)

<ion-list>
  <ion-item *ngFor="let studentName of studentNames; let i=index">
    <ion-label>{{studentName.name}}</ion-label>
    <ion-checkbox [(ngModel)]="studentName.checked" (ionChange)="checkboxToggle($event,studentName)"></ion-checkbox>
  </ion-item>
</ion-list>

我的模型(TypeScript)

@mycomp...
selectedItem: any;
studentNames: Array<{id: string, name: string, checked: boolean}>;

constructor(private navParams: NavParams, public storage: Storage) {
    // If we navigated to this page, we will have an item available as a nav param
    this.selectedItem = navParams.get('item');
    this.studentNames = [];
    this.readStorageAtStartup();
    console.log(this.studentNames)
  }

  public readStorageAtStartup() {
    this.storage.ready().then(() => {
       this.storage.forEach( (value: string, key: string, index: number) => {
         if(key.charAt(0)=="S") {
           this.studentNames.push({id: key, name: value, checked: true})
         }
       })
    })
  }

Console.log()(Firefox)

Array [  ]

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

将存储作为参数传递到readStorageAtStartup函数并从那里解析异步请求

public readStorageAtStartup(storage: Storage) {
storage.ready().then(() => {
   storage.forEach( (value: string, key: string, index: number) => {
     if(key.charAt(0)=="S") {
       this.studentNames.push({id: key, name: value, checked: true})
     }
   })
})

}