变量在 Angular9 中显示未定义

Variable shows undefined in Angular9

我是 Angular 9 的新手,因此 运行 遇到了问题。我正在使用 ionic 5 + Angular 9 当我尝试 console.log 时,变量显示为未定义。描述有点长,还请多多包涵

首先,我有以下回复:

{
"level_labels": [
    "Chapter",
    "Shloka"
],
"total_first_level_terms": 18,
}

我想将键的值推送到一个数组中,这样我的数组看起来像 [["Chapter","Sloka"],18]

我做了一个名为 heritage-texts.service 的服务,下面的函数从上面的响应中提取键的值:

    import { Injectable } from '@angular/core';
   import { HttpClient } from '@angular/common/http';
   import { HeritageText } from './heritage-texts.model';

    @Injectable({
        providedIn: 'root'
    })
    export class HeritageTextsService {

    toc = [];



   constructor(private http: HttpClient) { }

    getTOCHeritageText(heritageId : string) {

      this.fetchTOC(heritageId).subscribe(response => {


      for(const key in response){
        if( response.hasOwnProperty(key)) {
           this.toc.push(response[key]);
     }

   }

     console.log(this.toc});
  });
  return this.toc;
 }
 }

console.log(toc) 在调用函数时显示所需的数组。 这是我尝试 console.log ngOnInit():

上的变量的页面
 import { Component, OnInit } from '@angular/core';
    import { HeritageText } from '../heritage-texts.model';
    import { ActivatedRoute } from '@angular/router';
    import { HeritageTextsService } from '../heritage-texts.service';

   @Component({
     selector: 'app-heritage-text-detail',
     templateUrl: './heritage-text-detail.page.html',
     styleUrls: ['./heritage-text-detail.page.scss'],
     })
   export class HeritageTextDetailPage implements OnInit {

  loadedHeritagetextTOC;

  constructor(private activatedRoute: ActivatedRoute, private heritageTextsService: HeritageTextsService) { }

  ngOnInit() {

    this.activatedRoute.paramMap.subscribe(paramMap => {
      if(!paramMap.has('heritageId')) {
        return;
      }
      const heritageId = paramMap.get('heritageId');

      this.loadedHeritagetextTOC = this.heritageTextsService.getTOCHeritageText(heritageId);
      console.log(this.loadedHeritagetextTOC);

    });

  }


}

console.log(this.loadedHeritagetextTOC) 显示未定义。

当您处理异步可观察对象(HTTP 请求)时,您应该 return 它并仅在您的组件中订阅它。

您的服务:

getTOCHeritageText(heritageId: string): Observable<any> {
 return this.fetchTOC(heritageId);
}

你的组件:

ngOnInit() {
  this.activatedRoute.paramMap.pipe(
    // get your parameter value
    map(paramMap => paramMap.get('heritageId')),

    // switch it to a new observable, according to heritageId value
    switchMap((heritageId: string | undefined | null) => herigateId 
      ? this.heritageTextsService.getTOCHeritageText(heritageId)
      : of({}))
  ).subscribe((response: any) => 
      this.loadedHeritagetextTOC = Object.values(response));

}