Utilizing JSON data within a separate TypeScript function or within the ngOnInit lifecycle hook after successfully retrieving the data

I'm new to Angular and have a simple question. In my code, I have the following:

public jsonDataResult: any;
private getUrl = "../assets/data_3.json";

getScoreList(){
    this.http.get(this.getUrl).subscribe((res) => {
      this.jsonDataResult = res;
      console.log('Result: ', this.jsonDataResult.length);
    })
  }

onScoreFetch(){
    this.getScoreList();
    console.log('New Result : ' +  this.jsonDataResult.length)
}

ngOnInit(){
  this.getScoreList();
  this.onScoreFetch();
} 

The data displays correctly on my HTML page, but now I need to write a function using this data. Unsure of how to proceed, I attempted writing the onScoreFetch function. As a test, I wanted to see if displaying the length (this.jsonDataResult.length) would work outside of the getScoreList() function. Unfortunately, it did not work within the OnScoreFetch() method/function. Any suggestions?

I tried the following:

 onScoreFetch(){
    this.getScoreList();
    console.log('New Result : ' +  this.jsonDataResult.length)
}

While I expected "New Results" to show the length of "jsonDataResult," instead I received an error:

Error TypeScript: Cannot read properties of undefined (reading 'length')

Answer №1

    public fetchedData: any;
    private dataUrl = "../assets/data_3.json";
    
    ngOnInit(){
      this.fetchDataList();
    } 
    
          fetchDataList(){
                this.http.get(this.dataUrl).subscribe((response) => 
                  console.log('Response: ', response); 
                  if(response && response.length > 0) {
                   this.onDataFetch(response);
            }
          },
            error()=> { console.log('error message' , error);
     );
   }
        
      onDataFetch(fetchedData){
      console.log('Fetched Data',fetchedData);
    }

Answer №2

Check out this example:

let dataResponse: any;
const apiUrl = "../assets/data_3.json";

fetchData(){
    this.http.get(apiUrl)
    .pipe(map((response) => {
      return this.handleDataFetch(response);
    }))
    .subscribe();
  }

handleDataFetch(data:any){
    let dataLength = data?.length;
    console.log('Updated Data Length : ' + dataLength);
    return dataLength;
}

ngOnInit(){
  this.fetchData();
} 

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

Tips for accessing a variable from a Global service in Ionic

I am currently working on developing an app using Ionic but experiencing some difficulties. I encountered an issue while trying to access a variable from a global service when it is imported to another page. Here is an example of the Global service (backen ...

Jest.useFakeTimers() causing clearTimeout test to malfunction

I've been exploring the transition to the newer version of jest.useFakeTimers(), which is not set as default in the latest 27.x release. Encountering some issues during my tests, Jest keeps flagging that functions like clearTimeout and setInterval a ...

In Angular 2 Type Script service, make sure to include the @angular/core module for proper functionality as the 'require' method may not

I am encountering an issue with a service I am using. Whenever I try to start the page, I receive an error message. Here is the screenshot of the error: https://i.sstatic.net/WMzfU.png The compiled .js file contains the following code: reuired('@ang ...

What is the most effective method for merging two arrays in JavaScript?

Can a function be created to generate an array like the following? ["0-AA", "0-BB", "1-AA", "1-BB", "2-AA", "2-BB", "3-AA", "3-BB"] This particular function combines two array ...

React Typescript: exploring the power of dynamic types

Can dynamic typing be implemented? The JSON structure I am working with looks like this: { "fieldName": "Some text", "type": String, "inputType": "text" }, { "fieldName": "Some bool&q ...

You must include the formControlName within a parent formGroup directive

Upon creating a model-driven form, an error is encountered: Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class). ...

Error: Unable to Locate Module (Typescript with baseUrl Configuration)

Struggling to implement custom paths in my TypeScript project, I keep encountering the "webpackMissingModule" error due to webpack not recognizing my modules. I've attempted various solutions without any success. Any suggestions or ideas? Some packa ...

Managing a Angular HTTP Request on a Bottle Server where CORS is restricted

I am encountering an issue while trying to send data from my Angular 9 App to a bottle backend server. When running the application on the client side, I receive a CORS (Cross-Origin Resource Sharing) error indicating that the 'Access-Control-Allow-Or ...

Display permanent components in Angular while nesting components

Currently, I am incorporating the admin module within the main app module in my project Within the admin module, there are 2 components - register and login. Additionally, the admin module has its own routing module. Now, my task is to create a navbar sp ...

Combining types with additional features

Is it possible to configure the TypeScript compiler to generate an error when a function is called with an argument that can belong to both cases in a union type? For example: interface Name { name: string } interface Email { email: string } type ...

The back-end is not receiving the HTTP Get call, even though the URL is functional in the browser. The error message states that the JSON is

The backend function is functioning properly as both Postman and Swagger are able to call it without any issues. I decided to capture the URL string displayed in the error message and pasted it into a browser. Surprisingly, it successfully reached the bac ...

Having trouble accessing / encountering an error in Angular 6 and .NET Core 2.1 integration

While working on my Angular form in the Visual Studio .NET Core 2.1 template, I encountered an issue with displaying toast notifications. When running localhost, I received a "Cannot GET /" error. Additionally, after running ng build, various errors appear ...

Understanding Multiple Type Scenarios in React with Typescript

Code Demonstration: type PropsType = {top: number} | {bottom: number} // The function that moves something in one direction by a specific distance. function move(props: PropsType) { ... } Expected Usage: move({top: 100}) or move({bottom: 100}) Avoid us ...

Data is not displaying correctly in the Angular Material Table

I'm currently trying to build a mat table based on an online tutorial, but I'm facing a problem where the table appears empty even though I have hard coded data. As someone new to Angular and HTML/CSS, I'm struggling to understand why the ma ...

Exploring TypeScript: Understanding how to define Object types with variable properties names

Having an issue with a React + TypeScript challenge that isn't causing my app to crash, but I still want to resolve this lingering doubt! It's more of a query than a problem! My goal is to set the property names of an object dynamically using va ...

Retrieving selected values from a dynamic Primeng checkbox component

Within my Angular app, I am managing an array of questions. Each question includes a text field and an array of string options to choose from. The questions are retrieved dynamically from a service and can be updated over time. To allow users to select mul ...

Displaying an element in Angular 2 based on the selected option value

Looking for the most efficient method to display an element based on a selection from a dropdown menu in Angular 2. Despite trying various techniques, I have been unsuccessful in achieving the desired outcome! Below is the current implementation: HTML: ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

If an error 401 occurs, Angular 4 will redirect to the landing page

I am facing an issue with my Angular 4 app which has two modules: guest and user. When a user is not logged in and tries to navigate to .../user, it logs an error in the console. However, I am unable to locate the file responsible for handling this navigat ...

Error: Element type is invalid: a string was anticipated, but not found

I recently experimented with the example provided in React's documentation at this link and it functioned perfectly. My objective now is to create a button using material-ui. Can you identify what is causing the issue in this code? import * as R ...