数组中的Typescript元素不可访问

j.D*_*Doe 2 arrays typescript

这似乎是一个非常尴尬的问题:

我正在modal.service.ts使用以下代码进行访问: this.modalService.add('test');

我的modal.service.ts样子如下:

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

@Injectable({ providedIn: 'root' })
export class ModalService {
    private modals: any[] = [];

    add(modal: any) {
        // add modal to array of active modals
        this.modals.push(modal);
    }

    remove(id: string) {
        // remove modal from array of active modals
        this.modals = this.modals.filter(x => x.id !== id);
    }

    open(id: string) {
        // open modal specified by id
        const modal = this.modals.find(x => x.id === id);
        console.log(this.modals)
        console.log(this.modals[0])
        //modal.open();
    }

    close(id: string) {
        // close modal specified by id
        const modal = this.modals.find(x => x.id === id);
        modal.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么console.log(this.modals[0])给我undefined的时候this.modals给了我与“测试”是在pos 0阵列的输出?

这是控制台输出: 控制台输出

pet*_*szd 5

这是浏览器(或功能)的问题console。它表明的0元素this.modals是“测试”,因为在检查时是。但是在执行时,它是空的。

{
  const anArray = [];
  console.log(anArray);
  console.log(anArray[0]);
  anArray.push("foo");
}
// Browser's output:
// >>> []  <-- But expanded it will show [0: "foo"].
// >>> undefined

{
  const anArray = [];
  anArray.push("foo");
  console.log(anArray);
  console.log(anArray[0]);
}
// Browser's output:
// >>> ["foo"]  <-- See. Already pre-filled on display.
// >>> foo
Run Code Online (Sandbox Code Playgroud)

因此,您实际拥有的是比赛条件。您的电话this.modals被填充后open

  • 我不知道代码的其他部分是什么样,而且我不是Angular的专家。所以我无能为力。正确的做法是确保在“打开”之前调用“添加”。如果您不能保证,那就太复杂了。您可以尝试使用异步和/或promise。其他选择是具有`pendingModalOpenings`。如果模态尚不存在,则将在“ open”上填充。然后在`open`中,您将检查`pendingModalOpenings`中是否有任何等待,并根据需要打开刚刚添加的模态。 (2认同)