When trying to fetch and structure JSON data in Angular 6, the console displays "undefined" as the output

I'm currently exploring how to retrieve JSON data from an API, parse it, map it to my custom type, and then showcase it in an Angular Material datatable. Despite my efforts, the console output indicates that the value is undefined. I haven't even reached the stage of setting up the datatable yet.

Could someone please point out where I might be making a mistake? My development environment is based on Angular 6.1.0:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from '../../node_modules/rxjs';    

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})


export class AppComponent {
  title = 'NgTable';
  myPlace = "https://jsonplaceholder.typicode.com/posts";  
  myPosts: Observable<posts[]>;  
  myPostArr: posts[];

  constructor(http: HttpClient){
    this.myPosts = http.get<posts[]>(this.myPlace);
    this.myPosts.subscribe(response => {this.myPostArr = response});

    console.log(this.myPostArr);
  }
}

export interface posts {
  userId: number;
  id: number;
  title: string;
  body: string;
}

The console log displays: undefined

Answer №1

Since observables work asynchronously, data for this.myPostArr will be fetched at a later point in time. Therefore, outside of the subscribe block, it will not be resolved when that line of code is executed.

It is recommended to organize all your HTTP methods in a service and return Observables.

constructor(http: HttpClient){
    this.myPosts = http.get<posts[]>(this.myPlace);
    this.myPosts.subscribe(response => {
        this.myPostArr = response;
        console.log(this.myPostArr);
    });
}

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 on ensuring a certain HTML tag is used in the component interface

I developed a custom checkbox component that can receive children props from its parent interface CustomCheckboxProps { children?: string; } const CustomCheckbox = (props: CustomCheckboxProps) => { const { children } = props; return ( <di ...

methods for removing white spaces from json webservice output in asp.net

Hello everyone! I'm new to the world of JSON and this is my first experience with a webservice. I have successfully created an ASP.NET Webservice that returns JSON data. Everything seems to be working fine, but there is one issue I need help with. Wh ...

Converting a source-target-weight dataframe into a JSON file

I have these three dataframes - source, target, and weight : source target weight 0 A B 3 1 A C 2 2 B C 0 3 C D 1 4 D ...

Tips on how to effectively simulate a custom asynchronous React hook that incorporates the useRef() function in jest and react-testing-library for retrieving result.current in a Typescript

I am looking for guidance on testing a custom hook that includes a reference and how to effectively mock the useRef() function. Can anyone provide insight on this? const useCustomHook = ( ref: () => React.RefObject<Iref> ): { initializedRef: ...

Define the expected argument type of a function as an arrow function

In TypeScript, is there any way to enforce the use of arrow functions as function arguments? For instance, when using a publish-subscriber model and passing a listener function to a 'server' object, the server calls this function whenever a publi ...

What is the best way to create an array of unspecified classes that adhere to a particular interface in TypeScript?

Currently, I am working on an interface that has specific properties and function specifications which are implemented by several classes. My objective is to create an array of arrays that contain instances of these classes. However, when I try the followi ...

Setting a default value in a select tag with ngModel in Angular 6

I am currently working with Angular 6 and have the following code snippet: <select class="form-control form-control-sm" #ig="ngModel" [(ngModel)]="assetFormDetails.ig"> <option value="" >S ...

Having trouble converting NSData object to NSDictionary

Could there be an issue with the JSON output that is causing strange encoding when trying to extract information from a JSON file found on a blog? JSON: [{ "title": "A visit to McSorley\u0027s Old Ale House", "subtitle": "", "summary": "&bs ...

Utilizing Angular HTTP Interceptor to Show Loading Spinner Across Multiple Modules

My goal is to utilize the ng4-loading-spinner spinner when making HTTP calls to my API. I referred to the examples provided in the following resources: Angular Guide on Intercepting HTTP Requests/Responses Stack Overflow Post on Using HttpClient Interce ...

Utilizing Angular's async pipe to dynamically customize and assign values to variables

I have a parent component named A with over 20 child components, all of which extend A and are located within <ng-content></ng-content>. Within component A, I am updating the value of the showContent variable in multiple places. The issue aris ...

Retrieving a targeted JSON object array that has been input into a text box

My HTML file includes a textbox with a button that allows users to enter a course name. The JSON file contains an array of course objects with information about each course. My goal is to use Ajax with jQuery to loop through the JSON array when the user en ...

Does Angular 2/4 actually distinguish between cases?

I have a question about Angular and its case sensitivity. I encountered an issue with my code recently where using ngfor instead of ngFor caused it to not work properly. After fixing this, everything functioned as expected. Another discrepancy I noticed w ...

The parameter does not accept a string as an argument, it only allows for values of "one", "two", "three", "four", "five", or "six"

I'm facing a challenge with my specific type: type OtpCode = { one: string; two: string; three: string; four: string; five: string; six: string; }; I want to iterate through this object and assign values: Object.keys(defaultValues).forEac ...

Storing Python variables in JSON with formatted printing for better organization

Currently, I am extracting information from a CSV file using Python. Hello, I am conducting a test. After extracting the data, it is saved in a variable called text. My next task is to write this variable into a JSON file using json.dump(). However, ...

Ionic4: Troubleshooting the playback of audio files on a web-based application

Currently, my project involves using Ionic 4 in combination with Angular. I am facing a challenge where I need to play an audio file (mp3/wav) when an image is clicked. Despite working on this for a week, I have been unable to figure it out. Can anyone pr ...

Introducing cutting-edge intellisense for Typescript Vue in VSCode, featuring automatic import functionality specifically designed for the

Currently, I am working on a small project using Typescript and Vue in VSCode. In my setup, I have TSLint, TSLint Vue, Vetur, and Prettier plugins installed. Unfortunately, I am facing an issue with the intellisense "auto import" feature. It does not seem ...

"Error 404: The file you are looking for cannot be found on [custom company domain]. Please check

My attempts to retrieve a Google Drive file using its file ID with a service account in NodeJS have been unsuccessful. The requests are failing with an error indicating a lack of access: code: 404, errors: [ { message: 'File not found: X ...

What strategies can be implemented to restrict certain users from accessing specific components by manually altering the URL in Angular 2?

I am currently using Angular 2 to create a data table for displaying information. I have implemented a click event that redirects users to '/viewOutgoing;id=data_id', with the id corresponding to the data's id in the table. However, I need t ...

Angular Persistent States in Angular version 2 and beyond

Currently, I am in the process of transitioning an Angular 1.5.X application to Angular 4. Within my app, I incorporate Angular Ui-Router Sticky State from https://github.com/ui-router/sticky-states to prevent loss of content within my view when navigating ...

Incorporate the teachings of removing the nullable object key when its value is anything but 'true'

When working with Angular, I have encountered a scenario where my interface includes a nullable boolean property. However, as a developer and maintainer of the system, I know that this property only serves a purpose when it is set to 'true'. Henc ...