【问题标题】:Why is this Array undefined and how to fix?为什么这个数组未定义以及如何修复?
【发布时间】:2019-05-20 08:39:34
【问题描述】:

我的代码有问题。它说我的 Array 是未定义的,但后来的一个方法可以正常工作。代码如下:

books: IBook[] = [];
[...]
  ngOnInit() {
    this.service.getEmployees().subscribe(
      (listBooks) => this.books = listBooks,
      (err) => console.log(err)
    ); 
  }
[...]
 events: CalendarEvent[] = [
    {
      start: new Date(),
      end: new Date(),
      title: ""+this.books[0].device, //this.books[0] is undefined
      color: colors.yellow,
      actions: this.actions,
      resizable: {
        beforeStart: true,
        afterEnd: true
      },
      draggable: true
    },
[...]
test(){                     //this method is linked to a button
  console.log(this.books[0]) //after clicking it works fine
}
[...]

Test 方法在数组之后,它说它是“未定义”,所以它不能是未定义的,可以吗?

【问题讨论】:

  • getEmployees 是异步的,this.books 将在一段时间后分配。
  • 书籍:任何 = [];
  • @ErAbdulMeman 感谢您的回答,但没有成功
  • @RobertoZvjerkovic 你知道怎么解决吗?
  • 试试这个代码可能会起作用 --- 替换这个标题:""+this.books[0].device, ==> 标题:this.books[0]?" "+ this.books[0].device:' '

标签: arrays angular typescript undefined


【解决方案1】:

您在代码中的哪个位置执行此操作? :

 events: CalendarEvent[] = [
    {
      start: new Date(),
      end: new Date(),
      title: ""+this.books[0].device, //this.books[0] is undefined
      color: colors.yellow,
      actions: this.actions,
      resizable: {
        beforeStart: true,
        afterEnd: true
      },
      draggable: true
    },
[...]

如果此代码在 ngOnInit 方法中,则应将其放入订阅回调中,如下所示:

 ngOnInit() {
    this.service.getEmployees().subscribe(
      (listBooks) => {
         this.books = listBooks
         [...]
         events: CalendarEvent[] = [
        {
          start: new Date(),
          end: new Date(),
          title: ""+this.books[0].device, //this.books[0] is undefined
          color: colors.yellow,
          actions: this.actions,
          resizable: {
          beforeStart: true,
          afterEnd: true
         },
         draggable: true
        },
        [...]
      },
      (err) => console.log(err)
    ); 
  }

getEmployees 的调用是异步的,这意味着事件对象可能在 book 对象初始化的回调函数之前被初始化。 希望清楚

【讨论】:

  • 嘿@lchraf,这段代码在任何方法中都没有,数组就像一个变量
  • 嘿。那么同样的答案。您的事件数组在书籍装满之前被初始化。此语句标题:“”+this.books[0].device 应该在 book 属性被填充后完成。因此,您可以按照我在回答中的建议或在组件正文中使用标题为空的敏锐事件进行操作:标题:“”,然后在订阅回调中填写标题
【解决方案2】:

首先在ngOnInit 中运行的getEmployees() 是异步的。浏览器继续同步执行events 赋值,但listBooks 将在稍后从调用中解决。

因此,您应该在解析数据后修复您的逻辑并初始化events,并可能处理您期望的信息以防它未定义:

title: this.books[0] ? ""+this.books[0].device : ""

最后,当您要分配新数据时,您需要对 books 进行不可变操作:

this.books  = [...listBooks]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 2011-04-14
    • 2020-09-22
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 2014-04-11
    相关资源
    最近更新 更多