这个数组是不确定的,但是为什么呢?

时间:2019-05-21 13:24:33

标签: arrays angular undefined

我想检查一个数组,直到它填满并显示一个加载对话框,但它总是告诉我

  

this.events [0]未定义

ngOnInit() {
  this.initMethod();
  if(this.events[0].start == this.books[0].date_from_og) {
    this.dialog.closeAll();
  } 
}

但是事件不能不确定,因为它包含显示的日历事件。

  initMethod() {
    this.service
     .getEmployees()
     .subscribe(
     (listBooks) => {
       this.books = listBooks;
       this.events = this.books.map((book) => {
         return {
           start: new Date(book.date_from_og),
           end: new Date(book.date_to_og),
           type: ""+book.type,
           title: "" + book.device + "",
           color: colors.blue,
           actions: this.actions,
           resizable: {
             beforeStart: false,
             afterEnd: false
           },
           draggable: false
         }
       });
     },
     (err) => console.log(err)
   );
  }
}

和构造函数:

constructor(private modal: NgbModal, private service: BookingService, private dialog: MatDialog) {
   this.initMethod();

   this.dialog.open(DialogLaedt, {
      width: '650px'
   });

2 个答案:

答案 0 :(得分:0)

您的问题是您initMethod()异步检索结果。

因此,当您到达if(this.events[0].start == ...行时,就不能保证已经从服务中检索到了事件数据。

解决方法是将您的支票移到init方法的subscribe部分中(该方法在observable发出值时立即执行),或者让init方法返回可以订阅的observable,然后在其中执行检查该订阅。

解决方案1-将支票移入订阅

ngOnInit() {
  this.initMethod();
}

initMethod() {
  this.service
   .getEmployees()
   .subscribe(
   (listBooks) => {
     this.books = listBooks;
     this.events = this.books.map((book) => {
       return {
         start: new Date(book.date_from_og),
         end: new Date(book.date_to_og),
         type: ""+book.type,
         title: "" + book.device + "",
         color: colors.blue,
         actions: this.actions,
         resizable: {
           beforeStart: false,
           afterEnd: false
         },
         draggable: false
       }

       if(this.events[0].start == this.books[0].date_from_og) {
         this.dialog.closeAll();
       } 
     });
   },
   (err) => console.log(err)
 );
}

解决方案2-让您的initMethod返回一个Observable

ngOnInit() {
  this.initMethod().subscribe(() => {
      if(this.events[0].start == this.books[0].date_from_og) {
          this.dialog.closeAll();
      } 
  });
}


initMethod() {
    return this.service
    .getEmployees()
    .pipe(tap(
    (listBooks) => {
        this.books = listBooks;
        this.events = this.books.map((book) => {
        return {
            start: new Date(book.date_from_og),
            end: new Date(book.date_to_og),
            type: ""+book.type,
            title: "" + book.device + "",
            color: colors.blue,
            actions: this.actions,
            resizable: {
            beforeStart: false,
            afterEnd: false
            },
            draggable: false
        }
        });
    }))
}

答案 1 :(得分:0)

我注意到您两次调用 initMethod()。一次在构造函数中,一次在 ngOninit 方法中。