Ionic V4 JS 对象

Ionic V4 JS Object

在 Ionic-PouchDB 上工作 - 我对这两个都是新手 - 并且对 JS 非常基础。

我有一项服务 returns 来自 PouchDB 的数据和一个填充视图的 ngfor 循环。工作正常

来自页面打字稿

ngOnInit() {
    this.slates = this.api.getSlates();
    }

来自HTML

 <ion-content>
  <ion-list>
    <ion-item button detail lines="inset" *ngFor="let slate of slates" (click)="openDetails(slate)">
  {{ slate.createdon | date:'EEE  - d - LLL hh:mm a yyyy' }} --- {{ slate._id }}
</ion-item>
</ion-list>
</ion-content>

如果我 console.log this.slates 我得到 到目前为止一切顺利

我需要找出看起来像数组的对象中有多少个对象 - 在本例中为 10 个。还需要能够获取每个元素中的数据。 例如来自对象的 _id 或类型

如果我说

ngOnInit() {
    this.slates = this.api.getSlates();
    console.log(this.slates);
    console.log(Object.keys(this.slates));
}

我刚得到一个空数组。

非常感谢任何帮助 - 它会帮助我理智。

要获取数组的长度,请使用

this.slates.length

Object.keys(this.slates) returns 来自键值对的键

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

对于第一部分,您可以使用

const numberOfSlates = this.slates.length;

对于第二个,您可以使用 find() 获得第一个结果:

const targetId = "slate:1546427619624:cameraa:x:5";
const foundItem = this.slates.find((slate) => slate["_id"] === targetId);

更新 - 为什么长度 = 0?

根据您的评论,您在之后检查时看到的长度为零。

你是对的,这是因为操作是异步的,所以它不会立即填充。

没有看到你的 .getSlates() 的代码,这只是一个猜测,但如果它 returns 是一个承诺,那么你可以这样做:

ngOnInit() {
    this.api.getSlates().then((res) => {
       this.slates = res;
       console.log(this.slates);
       console.log(this.slates.length);
    });
}