What causes the data fetched from a service to become undefined upon subscription in Angular?

I have created an interface as follows:

export interface IEmployee
{
    maNV?:number,
    hoTen?:string,
    gioiTinh?:string,
    ngaySinh?:Date,
    diaChi?:string,
    cmnd?:string,
    sdt?:string,
    luong?:number,
    ngayBatDauLam?:Date,
    maNguoiQuanLy?:number,
    isDelete?:boolean
}

In a file named employee.json, I have stored information about some employees:

[
    {"maNV":1,"hoTen":"nguyen quang du","gioiTinh":"nam","ngaySinh":"03/02/1999","diaChi":"Hà Tây","cmnd":"1131131231231232","sdt":3123123141,"luong":300,"ngayBatDauLam":"03/01/2020","maNguoiQuanLy":1,"isDelete":false},
    {"maNV":2,"hoTen":"nguyen thi duyen","gioiTinh":"nu","ngaySinh":"03/02/1999","diaChi":"Hà Tây","cmnd":"1131131231231232","sdt":3123123141,"luong":300,"ngayBatDauLam":"03/01/2020","maNguoiQuanLy":1,"isDelete":false},
    {"maNV":3,"hoTen":"khuat quang chien","gioiTinh":"nam","ngaySinh":"03/02/1999","diaChi":"Hà Tây","cmnd":"1131131231231232","sdt":3123123141,"luong":300,"ngayBatDauLam":"03/01/2020","maNguoiQuanLy":1,"isDelete":false}


]

To fetch the data of employees from employee.json, I have created a service:

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http'
import {IEmployee} from './employee/employee'
import {Observable} from 'rxjs'
@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  private _url:string="../assets/data/employees.json";
  constructor(private http:HttpClient) {}
  getEmployees():Observable<IEmployee[]>
  {
    return this.http.get<IEmployee[]>(this._url);
  }
}

Subsequently, I created a component to retrieve the employee data using the method getEmployee(). The main code snippet looks like this:

public data:Array<IEmployee>;
constructor(private service:EmployeeService){}
ngOnInit():void
{
this.service.getEmployees().subscribe(data=>this.data=data) ;
console.log(this.data);
}

However, upon inspection, I discovered that this.data is being displayed as undefined. I am unsure why this is happening, especially since I have defined it as type Array<IEmployee>. Can someone please assist me in converting it correctly?

Answer №1

The reason for this issue is that the logging of data is happening before it is being fetched by the httpClient. It's important to remember that httpClient.get is an asynchronous method. To resolve this, you can move the console.log inside the subscription block like shown below:

ngOnInit(): void {
    this.service.getEmployees().subscribe(data => {
        this.data = data;
        console.log(this.data);
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing Store.getState() to return an 'any' type following the implementation of rootReducer with combinedReducers?

Seeking assistance with utilizing a root reducer to encapsulate my combined reducers for the purpose of resetting them upon a reset store action. However, I am facing an issue where I cannot directly access the reducers using Store.getState().recuder1 ...

Best practices for stubbing an element in order to effectively unit test a LitElement component

Trying to perform unit tests on LitElement components has been quite a challenge for me. I found myself stuck when attempting to isolate components, particularly in figuring out how to stub elements effectively. The Polymer project provides some informatio ...

typescript push in react native is a crucial step to enhance performance and optimize

I've been diving into TypeScript within the realm of React Native. Oddly, when I translated a certain snippet to vanilla JavaScript, the application worked flawlessly. However, upon converting it back to TypeScript, an error message popped up stating ...

When executing the "node app.js" command, the <app-root> element appears empty in the browser

After creating an Angular 7 application with the Angular CLI and adding my express server, I encountered a strange issue. When starting my app with the command "node server/app.js", the browser displayed <app-root></app-root> in the "Elements" ...

Press the button on a different component located at the same level

In the first component, I am utilizing Websocket to receive data. When receiving a specific value, I need to update the status of a button in the second component to "disconnect." Despite using an event emitter for this purpose, it is currently not funct ...

Evaluate the Worth of a Property Established in a Subscription

Currently, I am using Jasmine for testing an Angular application and facing a challenge in testing the value of a property that is set within the subscribe call on an Observable within the component. To illustrate this point, I have created an example comp ...

Sending data to Dialog Component

While working on implementing the dialog component of material2, I encountered a particular issue: I am aiming to create a versatile dialog for all confirmation messages, allowing developers to input text based on business requirements. However, according ...

Experimenting with parallelism using TypeScript/JS

Currently, I am tackling a TS project that involves testing concurrent code and its interactions with a database, specifically focusing on idepotency. My goal is to ensure that multiple requests modifying the same resource will either apply changes correct ...

Properties of a child class are unable to be set from the constructor of the parent class

In my current Next.js project, I am utilizing the following code snippet and experiencing an issue where only n1 is logged: class A { // A: Model constructor(source){ Object.keys(source) .forEach(key => { if(!this[key]){ ...

How can you establish a TypeScript project that employs classes shared by both client and server applications?

I am working on a project that consists of two components: ServerApp (developed with nodejs using NTVS) and BrowserApp (an Html Typescript application). My goal is to share classes between both projects and have immediate intellisense support. Can you pr ...

Transfer the formControl to the parent component

Each input in the child component is defined with formControl in the code below. If I wanted to shift this definition to the parent component, what would be the new implementation? Parent Component HTML: <div class="col-6"> <form (ngSubmit)=" ...

Request for /Account after Keycloak token request in Angular app

I have been working on an Angular and Keycloak project. I followed a tutorial that helped me integrate Keycloak into Angular, which can be found here: https://www.npmjs.com/package/keycloak-angular My public client is able to request a token, but when it ...

I am in need of a customized 'container' template that will display MyComponent based on a specific condition known as 'externalCondition'. MyComponent includes the usage of a Form and formValidation functionalities

container.html <div ngIf="externalCondition"> <!--Initially this is false. Later became true --!> <my-component #MyComponentElem > </my-component> <button [disabled]= "!myComponentElemRef.myDetailsF ...

Encountering a 401 error in Ionic 2 when making a post request to the WP-REST API, even though

I'm currently working on a simple application to manage posts in Wordpress using the wp-rest api. Everything, including creating, updating, and deleting posts, works perfectly fine when tested in Postman. I am also able to fetch posts successfully usi ...

Loading fonts using next.js and style jsx

I've recently started the process of converting my create react app to next.js. As a reference, I've been using Vercel's open source Next.js website to help me structure my own. In order to implement custom fonts, I created a font.ts file an ...

Tips and tricks for utilizing window.external in Angular 2

I am trying to implement a call from window.external in Angular 2 and pass a JSON as a parameter. Here is an example similar to what I am trying to achieve: C# [System.Runtime.InteropServices.ComVisibleAttribute(true)] public class ScriptInterface ...

Dispatch a websocket communication from a synchronous function and retrieve the information within the function itself

I am currently working on an Angular project and need guidance on the most effective approach to implement the following. The requirement is: To retrieve an image from the cache if available, otherwise fetch it from a web socket server. I have managed ...

Issue with Ionic Framework Typescript: `this` variables cannot be accessed from callback functions

Is it possible for a callback function to access the variables within this? I am currently working with d3.request and ionic 3. I can successfully make a REST call using d3.request, but I am facing difficulty when trying to assign the response to my this. ...

Transform an Array into a String using Angular

Is there a more efficient way to extract all the state names from the array (testArray) and convert them to strings ('Arizona','Alaska','Florida','Hawaii','Gujarat','Goa','Punjab'...)? ...

Angular: When making an HTTP GET request, receiving an OPTIONS 405 error message indicating that the method is

I'm facing an issue with my API when making an HTTP GET request - it returns OPTIONS 405 (Method Not Allowed). Access to XMLHttpRequest at 'apiurl' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to ...