【问题标题】:Getting undefined error when tried to access loop variables from ngOnInit() in angular尝试从 ngOnInit() 以角度访问循环变量时出现未定义的错误
【发布时间】:2020-08-11 22:08:20
【问题描述】:

在 ngOnInit() 函数中,我从服务接收数据以在我的组件的其余部分中使用。它在订阅之外的任何地方都未定义。我不知道为什么。

import { Component, OnInit, Renderer2, HostListener,ViewChild, TemplateRef, Inject} from '@angular/core';
    import { DOCUMENT } from '@angular/common';
    import { NgbModalOptions, NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-pattern',
  templateUrl: './pattern.component.html',
  styleUrls: ['./pattern.component.scss']
})

export class PatternComponent implements OnInit {


  public config: any = {};

  constructor(@Inject(DOCUMENT) private document: any,private modal: NgbModal,private pattern:patternService) { }

  ngOnInit(): void {

   this.pattern.Pattern(this.local).subscribe(
      data => {

      for (var i = 0; i < this.length1; i++){
         this.visitedArray[temp1] = [false, this.Patternarray[i]]; //I'm trying to access this in onselect() function. If the value is false I'm trying to do something
         console.log("Visited Array ng:",this.visitedArray[temp1]);
        }
       },
      err => {
        console.error(err);
      }
    );
 }
}

这是我的 onselect() 函数,我尝试从 ngOnit 访问 (this.visitedArray[this.temp1]),但无法访问它。 'Visited Array:' undefined 打印在控制台中

onselect(row, i) {

      console.log("Visited Array:",this.visitedArray[this.temp1]);
       console.log("visited id:",this.visitedArray[this.temp1][0]);

    }

【问题讨论】:

  • 订阅 observable 是一种异步模式。只有在将数据分配给this.visitedArray 变量后,您才需要调用onselect()。只有在为 this.visitedArray 变量赋值后调用订阅内的 onselect() 函数才能确保这一点。

标签: angular typescript


【解决方案1】:

这里的服务调用是异步的,所以subscribe 之外的代码将首先执行,而订阅内部的代码将在服务返回数据后执行(这可能需要一些时间)。因此,您试图在变量获得其值(即在订阅内)之前访问它,这给出了未定义的值。

解决方案是在数据到达后开始处理您的数据(即在subscribe 内部)

【讨论】:

    【解决方案2】:

    简而言之,只需这样做:

    this.pattern.Pattern(this.local).subscribe(
          data => {
          this.length1 = this.patterns.length;
          this.visited_count=this.length1-1;
         for (var i = 0; i < this.length1; i++) {
              this.Patternarray[i] = this.questions[i].Id;}
         for (var i = 0; i < this.length1; i++){
             this.visitedArray[temp1] = [false, this.Patternarray[i]]; //I'm trying to access this in onselect() function. If the value is false I'm trying to do something
             console.log("Visited Array ng:",this.visitedArray[temp1]);
            }
    onselect(row,i); // call onselect from here
           },
          err => {
            console.error(err);
          }
        );
    

    【讨论】:

      猜你喜欢
      • 2021-08-30
      • 2022-06-21
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多