Currently, I am in the process of developing a website using the MEAN stack for a project. My focus is on handling the front end operations, specifically on retrieving and storing data from an API into an array for future use. However, I seem to be encountering a peculiar issue.
My goal is to import an array that contains latitude and longitude coordinates for all countries worldwide.
The service I have created looks like this:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Country } from '../models/country';
@Injectable({
providedIn: 'root'
})
export class DataService {
REST_API_SERVER = 'http://localhost:3000/countries/getCountries';
constructor(private httpClient: HttpClient) { }
getCountryData(): Observable<Country[]>{
return this.httpClient.get<Country[]>(this.REST_API_SERVER);
}
}
In this code snippet, Country
represents a class with specific attributes.
To utilize this function, I call it within my component.ts file as shown below:
import { Component, OnInit, AfterViewInit, ViewChild, ElementRef, HostListener, Host } from '@angular/core';
import { Country } from '../models/country';
import { DataService } from '../services/data.service';
export class GlobeComponent implements AfterViewInit {
listOfCountries!: Country[];
constructor(private countryService : DataService) {
}
ngOnInit() {
this.countryService.getCountryData().subscribe((countries) => {
this.listOfCountries = countries;
});
}
Although, when attempting to access listOfCountries
, I encounter difficulties. For instance, the error message displays:
ERROR TypeError: Cannot read property 'length' of undefined
Interestingly, by adding a console.log statement within the ngOnInit()
function:
console.log("Country printed in ngOnInit : " + this.listOfCountries[0].Entity);
It seems to start functioning correctly. Yet, now a new error arises:
ERROR TypeError: Cannot read property '0' of undefined at GlobeComponent.ngOnInit
This situation has left me puzzled. Why does the console.log statement populate the array, but the error persists regarding its undefined status? Despite the console.log workaround enabling normal array access and utilization, I prefer not to use it. Any advice on where my mistake lies would be highly appreciated!