0

在 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]);

    }
4

2 回答 2

2

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

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

于 2020-04-28T07:01:55.670 回答
1

简而言之,只需这样做:

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);
      }
    );
于 2020-04-28T08:03:25.110 回答