ion-list display asynchronously added data to arra

2019-08-28 21:08发布

I am new in ionic. I trying to make an app which will search for Bluetooth devices and will display them. I have created a service which search for Bluetooth devices. When a device found an event publishes like below:

this.event.publish("ibeacon", newBeacon);

Here is my event injection:

import { Events } from 'ionic-angular/util/events';
......
constructor(private event: Events){}

Here is how I subscribe to the event in order to get the published data:

this.event.subscribe("ibeacon", (newBeacon) => {
  this.iBeacons.push(newBeacon);
});

As you can see I have declared an iBeacons Array where I push my received objects. The problem is when I try to display the iBeacons Array contents nothing displayed. Here is how I display my array:

<ion-content padding>

  <ion-list>
   <ion-item *ngFor="let beacon of iBeacons">
     <ion-label>
      {{ beacon.hash }}
     </ion-label>
   </ion-item>
 </ion-list>

</ion-content>

The array at the beginning is empty. I have have checked and I receive correctly my devices when I subscribe to the event. I don't get errors. I thing the data is not displayed because the data is added asynchronously in iBeacons array. Any idea?

Here are some of the iBeacons Array contains:

(4) [{…}, {…}, {…}, {…}]
0: {hash: "b5d787ac973341a59bf73838eededcb4", uuid: "fda50693-a4e2-4fb1-afcf-c6eb07647825", major: "10001", minor: "10301", lastFoundTime: 1518003454401}
1: {hash: "50aee081c9833e51ce00b9aa4a0c062d", uuid: "fda50693-a4e2-4fb1-afcf-c6eb07647825", major: "10001", minor: "10206", lastFoundTime: 1518003454391}
2: {hash: "1c8ecafb6efbbc37f905d95551291672", uuid: "fda50693-a4e2-4fb1-afcf-c6eb07647825", major: "10001", minor: "10208", lastFoundTime: 1518003454391}
3: {hash: "442e383d9c582985083b5b05f07161d2", uuid: "fda50693-a4e2-4fb1-afcf-c6eb07647825", major: "10001", minor: "10205", lastFoundTime: 1518003454392}
length: 4
__proto__: Array(0)

Here is the iBeacons array initialization:

iBeacons:any [] = [];

1条回答
做自己的国王
2楼-- · 2019-08-28 21:51

Try to use ChangeDetectorRef like this:

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

constructor(private cd: ChangeDetectorRef) {}

this.event.subscribe("ibeacon", (newBeacon) => {
  this.iBeacons.push(newBeacon);
  this.cd.detectChanges();
});
查看更多
登录 后发表回答