When attempting to fetch JSON data using the Angular 2 `http.get()` method, the data returned is undefined and the component does not reflect any

My http-data.service is set up to accept json for output in the component template. Initially, the console displays that the first few calls return undefined, while subsequent calls start returning json. However, upon checking the component, it is evident that the method responsible for outputting the data to the component is only called once. As a result, since the data has not arrived yet, it shows undefined and does not update even after the json has arrived. Can someone please help explain why this is happening? Thank you.

Code snippet from my http-data.service:

            
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class HttpService{
    constructor(private http: Http) {}

    getDataOrganizations(): Observable<any[]>{
        return this.http.get('http://localhost:3010/data')
            .map((resp:Response)=>{
                let dataOrganizations = resp.json().organization;
                return dataOrganizations;
            });
    }

    // Other similar methods follow here...

}

Snippet from my data-all.service


import { Injectable, EventEmitter } from '@angular/core';
// Other imports...

@Injectable()
export class ModuleDataService {
    // Constructor and other properties/functions...

    private currentPopupView: EventEmitter<any> = new EventEmitter<any>();

    // More properties and functions...
}

Snippet from my left-block.component


import { Component, OnInit} from '@angular/core';
// Other imports...

@Component({
    // Component setup details...
})
export class ModuleLeft implements OnInit{

    modules: ModuleModel[];

    constructor(private modulesAll: ModuleDataService){}


    ngOnInit(){
        this.modules = this.modulesAll.getDataModules();
        console.log("view");
        console.log(this.modulesAll.getDataModules());
    }

    onToggle(module: any){
        this.modulesAll.toggleModules(module);
    }
}

In my component, the this.modulesAll.getDataModules() method seems to be executed only once without updating (console logs => undefined). If anyone has any insights or thoughts on this issue, I would appreciate some help. Thanks.

Answer №1

Due to the nature of the .subscribe() method not waiting for data arrival, it seems you're familiar with this issue already. The challenge lies in subscribing to the getDataModules() service incorrectly. It's important not to subscribe to a service within another service (at least not in this scenario). Move the subscription method to the left-block.component and everything should function as intended.

getDataModules() {
  this.httpService.getDataModules().subscribe(((modules) => {
    this.dataModules = modules;
    console.log(this.dataModules);
  }));
  console.log('dataModules');
  console.log(this.dataModules);
  return this.dataModules;
}

Here is an example of how it should be structured:

@Component({
  moduleId: module.id,
  selector: 'modules-left-block',
  templateUrl: './modules-left-block.html',
  styleUrls: ['modules-left-block.css']
})
export class ModuleLeft implements OnInit {

  modules: ModuleModel[] = new ModuleModel();

  constructor(private modulesAll: ModuleDataService, private httpService: HttpService) {}


  ngOnInit() {
    this.getDataModles();
    //this.modules = this.modulesAll.getDataModules();
    console.log("view");
    //console.log(this.modulesAll.getDataModules());
  }

  onToggle(module: any) {
    this.modulesAll.toggleModules(module);
  }

  getDataModules(): void {
    this.httpService.getDataModules().subscribe(((modules) => {
      this.modules = modules;
      console.log(this.dataModules);
    }));
  }

}

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

The function URL.createObjectURL() is failing to work across all browsers

Despite my efforts, I'm feeling tired as none of the solutions seem to work for me. Here is the HTTP call in Angular that I am struggling with: $http({ method: 'GET', url: API_URL + 'v1/file/' + candidateId + '/download& ...

Tips for recognizing and unraveling a nested json document into individual columns of a dataframe

I am revising my question once more to make it clearer. Here is a snippet of my data. { "Research": { "@xmlns": "http://www.xml.org/2013/2/XML", "@language": "eng", "@create ...

TypeScript requires that the `includes` function must have the same type parameter for both input and

When working with TypeScript, I've encountered an interesting dilemma regarding the use of the Array.Prototype.includes function. It seems that this function requires me to pass in the same type as in the original array, but isn't the purpose of ...

Browser refusing to acknowledge jQuery/JavaScript (bootstrap)

Here is where I include the necessary jQuery libraries and my custom jQuery code: <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <script src= ...

Encountering a compile error with a Next.js React project that cannot be resolved

Encountered an issue while refreshing my project with the command "npm run dev" and reloading the site locally. The console displays "Compiled /not-found" and the site fails to load completely. In addition, none of the elements animated via framer motion ...

Launching the Node.js application on Heroku resulted in encountering an issue: "Application error - There was a problem within the application

When I access the browser using http://localhost:8080/, I can see the message Hello World with Express. I am currently trying to deploy this application on Heroku. I have followed the tutorial provided by Heroku. 1) Create a new app 2) Choose an App name ...

Getting a character type on the client side of GWT: a guide

com.google.gwt.json.client.JSONParser.parseStrict(jsonStr) is encountering a syntax error when the JSON string includes non-printable or unrecognized Unicode characters. As a result, I am attempting to eliminate these non-printable Unicode characters on th ...

Typescript: Potential null object error when defining a method

I recently encountered an error message stating "Object is possibly null" while working on the changePageSize method in book-store.component.html. It seems like I need to initialize the object within the class, but I'm not familiar with how to do that ...

Share the component with css and font via npm

I am looking to release an angular 2 component on NPM. This particular component utilizes CSS that references certain fonts. I have figured out how to publish the .ts files, but I am unsure about how to handle the CSS and font files. Here is what I curren ...

What strategies can be implemented to minimize the use of if-else statements?

Is there a more efficient way to simplify this if-else statement? This code dynamically changes the picture based on integers retrieved from the database. I am looking for ways to optimize this code. if (val["soil_h"] < 21){ $("#ground").att ...

Using rxjs for exponential backoff strategy

Exploring the Angular 7 documentation, I came across a practical example showcasing the usage of rxjs Observables to implement an exponential backoff strategy for an AJAX request: import { pipe, range, timer, zip } from 'rxjs'; import { ajax } f ...

Incapable of acquiring the classification of the attribute belonging to the

Is it possible to retrieve the type of an object property if that object is stored in a table? const records = [{ prop1: 123, prop2: "fgdgfdg", }, { prop1: 6563, prop2: "dfhvcfgj", }] const getPropertyValues = <ROW extends o ...

Using space as a separator for thousands when formatting integers

In an attempt to change the appearance of 1000 to resemble 10 000, I found numerous examples online on how to add a separator such as a comma or some StringLocal. However, I am looking for a way to use a space instead. Can anyone advise me on which locale ...

Most effective method for structuring a JSON format that contains recurring keys for every item within its array

Currently, I'm creating a JSON object that includes multiple addresses. My main concern is the potential for the JSON size to grow too large, which could impact browser performance and parsing speed in JavaScript. Each address includes keys such as "I ...

Javascript: recursive function fails to return existing value

I'm attempting to recursively loop through an array in search of a key that matches a specified regex pattern. Once the condition is met, the loop should halt and return the value of the key. The issue I am facing is that although the loop stops corr ...

Comparison of valueChanges between ReactiveForms in the dom and component级主动形

Is there a method to determine if the change in valueChanges for a FormControl was initiated by the dom or the component itself? I have a scenario where I need to execute stuff() when the user modifies the value, but I want to avoid executing it if the v ...

Javascript error - SyntaxError: unexpected token '}' after property list is missing

In my code snippet below: var UserCharacter = { UserID: util.getCookie('u_u'); userUsingThisCharacter: function() { var data = {}; data.UserID = UserCharacter.UserID; $.ajax({ type: "GET", url: util.API_URL + "charact ...

Discover the power of sharing a service instance in Angular 2 RC5

In the past, I shared a service instance by declaring it as a viewInjectors within my @Component like so: @Component({ selector: 'my-sel', viewInjectors: [SharedService], templateUrl: 'template.html', pipes: [MyPipe] }) ...

Incorporating JQuery Plugin into Angular 2 Component

Currently, I am attempting to incorporate a jQuery code snippet into a component that I acquired online. This is the specific component. Although I have successfully integrated the HTML and CSS into the code, I am encountering difficulties with loading th ...

Chrome mistakenly identifying octet-stream as a .png image

My application incorporates the use of Google Maps API V3 and ASP.Net, utilizing OverlayView to customize icons on the map. The icon's image is configured within the onAdd event by dynamically adjusting the background CSS property using JavaScript. T ...