Search code examples
angularangular-servicesionic5

Variable shows undefined in Angular9


I am new to Angular 9 and hence running into problems. I am using ionic 5 + Angular 9 A variable shows as undefined when I am trying to console.log it. The description is bit long, please bear with me.

To start with, I have the following rest response:

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

I want to push the values of the keys into an array, so that my array looks like [["Chapter","Sloka"],18]

I have made a service named heritage-texts.service, and the following function extracts the values of the keys from the response above:

    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) shows the array as desired when the function is called. This is the page where I am trying to console.log the variable on 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) shows undefined.


Solution

  • As you're dealing with asynchronous observables (an HTTP request), you should return it and subscribe to it just in your component.

    Your service:

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

    Your component:

    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));
    
    }