Is JSON data loading causing an undefined object in Angular 2? Could it be due to asynchronous loading

...component.ts:

import { Component } from '@angular/core';
import { ValgteSkolerService } from '../valgteSkoler.service';
import { DatoService } from './datoer.service';

@Component({
    selector: 'kalender',
    providers: [DatoService],
    templateUrl: 'app/kalendervisning/html/kalender.html'
})
export class KalenderComponent {

    private selectedSchoolRoutes: Array<any> = [];
    public dates: any[] = [];

    constructor(private selectedSchoolService: ValgteSkolerService, private dateService: DatoService) {
        this.dateService
        .getDate()
        .subscribe(dates => { this.dates = dates; });
    }

    ngOnInit() {
      this.selectedSchoolService.fetchStoredData();
      this.selectedSchoolRoutes = this.selectedSchoolService.sharedSelectedSchoolRoutes;
    }

    routeCount: number = 0;
    j: number = 0;

    weekOne(month: number, year: number) :Cell[] {
        var cells: Array<Cell> = [];
        this.routeCount = 0;
        for (this.j = 1; this.j <= this.totalDays(month, year); this.j++) {
            var cell = new Cell;
            console.log(this.dates[this.j].date);
            cell.id = this.dates[this.j].date;
            cell.text = this.j;       
            cells.push(cell);
            this.routeCount++;
            this.j = this.j;
            if (this.routeCount % 7 == 0 && this.routeCount != 0) {
                break;
            }
        }
        return cells;
    }

class Cell {
    id: string;
    text: number;
}

...service.ts:

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

@Injectable()
export class DatoService { 

    date: Array<any>;

    constructor(private http: Http) {}

        getDate() {
            return this.http.request('app/kalendervisning/datoer.json')
                 .map(res => res.json());
        }   
}

...json:

{
        "date": "2016-08-01"
    },
etc.

I am facing challenges with the

cell.id = this.dates[this.j].date
statement in the component. Upon inspecting the browser, it appears that the dates array is undefined until the entire code has been executed multiple times. Eventually, the array populates. When I examined this using console.log, it shows 9 undefined objects followed by the actual data, repeated twice inexplicably. I suspect there might be an issue with the asynchronous loading of data, but I'm uncertain. Could you offer any insights into why this behavior occurs and suggest a solution?

Answer №1

Make sure to include the API call in the constructor code within the ngOnInit method:

ngOnInit() {
  this.DatoService
    .getDato()
    .subscribe(dates => { this.dates = dates; });

  this.selectedSchoolsService.retrieveStoredData();
  this.selectedSchoolRoutes = this.selectedSchoolsService.sharedSelectedSchoolRoutes;
}

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

`On the first date chosen, activate an event within the ngx-bootstrap daterangepicker.`

I am utilizing a date range picker with the following code: <bs-daterangepicker-inline [bsValue]='bsValue' (bsValueChange)="test()"></bs-daterangepicker-inline>. Is there a way to trigger an event when the first date is sel ...

What is the best way to implement an asynchronous fetch function in React that will provide a usable output for constructing conditional statements?

I've developed a custom fetch function for my React application: const getStatus = () => { const fetchData = async () => { const response = await fetch(`http://localhost:3000`); const result = response.status; console.l ...

Angular 17: Issue with _HttpClient Provider Not Found in Standalone Component Utilizing ApiService

I have been developing a cutting-edge Angular 17 application that integrates the Spotify API using the innovative standalone component functionality. However, I am facing an issue while attempting to inject the HttpClient into a service. Despite meticulous ...

Is there a way to make this variable function properly within the google.maps.LatLng() method?

I've been working on a function that goes through some JSON data and retrieves latlong information to be displayed inside google.maps.LatLng(). The issue I'm facing is that I keep getting a null return and I can't seem to identify the reason ...

Retrieving routing information from directives within angular2

const APP_ROUTES: RouterConfig = [ { path: 'app/home', component: HomeComponent, data: { name: 'Home' } } ] Assuming the route configuration is set as displayed above, how can one ...

Jest unit tests are failing due to an error stating that VUE_APP_CONFIG is not defined

export interface VueAppSettings { BASE_URL: string; BASE_URL_V2: string; } declare const VUE_APP_SETTINGS: VueAppSettings; export const APP_SETTINGS = { ...VUE_APP_SETTINGS } as const; I am encountering a reference error in the code snippet abov ...

Converting an HTML page into a base 64 string: Step-by-step guide

Currently, I am utilizing Angular 6 for my project. On the index page, I am binding data and then submitting it to the database. My objective is to submit the entire HTML page with the bound data as a string in the database. Is there a way to convert an H ...

Having trouble retrieving object properties within an Angular HTML template

There are two objects in my code that manage errors for a form: formErrors = { 'firstname': '', 'lastname': '', 'telnum': '', 'email': '' } ValidationMessa ...

Is there a way to easily find the repository URL for each package listed in the package.json file using the command line interface

Imagine you have the following entries in your package.json file: "autoprefixer": "^7.0.1", "bower": "^1.8.0", "browserstack": "^1.5.0", "canonical-path": "0.0.2", "cheerio": "^0.22.0", "clean-css": "^4.1.2", "colors": "^1.1.2", "glob": "^7.1.1", "grunt": ...

Compressing JSON objects for push notification delivery on iOS and Android platforms with PHP

I am sending the push notifications in the chat module using curl for IOS and FCM for android. In which we are sending some of our database entities to enable users to share our in-app content with each other. Scenario: As a third party, I am using pushe ...

Should I be decoding strings from the server like this in my JavaScript code?

When retrieving JSON data from an ASP.NET web service that has been HtmlEncoded using Microsoft's AntiXSS library (Encoder.HtmlEncode()), and returned as JSON through a jQuery Ajax call, I am faced with the task of setting this data on form inputs. O ...

Retrieving JSON data in Angular 5 returns a 400 bad request error

Having trouble calling the REST API of Amazon S3 from Angular 5. Keep getting a 400 bad request error. This problem has been persisting for a while now and I really need to find a solution or at least get some suggestions on where the issue might be. Her ...

What is the correct way to specify an image path for a background URL?

Currently, I am setting a background image for the hr tag using the following code: <hr style="height:6px;background: url(http://ibrahimjabbari.com/english/images/hr-11.png) repeat-x 0 0;border: 0;margin:0px!important"> However, I have now saved th ...

Is there a way to set up a background process within electron that captures a screenshot of the entire desktop?

I'm currently working on a Desktop application using Angular2 and Electron that captures screenshots of the entire desktop and saves them to a specified path on my PC. The code for capturing screenshots is implemented in the app.component.ts file, but ...

Do we really need to implement a loading observable toggle for our observables?

While considering different container templates, I noticed that some load data in the following way: <ng-container *ngIf="!(loading$ | async); else tpl"> When the client is retrieving data (such as Post instances), it will update the loading$ obser ...

Encountered an issue with the Angular proxy while attempting to include an email in the

When developing a reset password module using Angular, I encountered an issue with sending an email verification request to the backend for validation. To handle this, I set up a proxy in my code as follows: "/api": { "target": &quo ...

Tips on accessing the JS file api within an angular component.ts file

I've got a function in my JS file located at src/server/js/controller.js, and I'm trying to use that API within a component's ts file. I attempted the following code to achieve this but it doesn't seem to be working properly. controlle ...

Unveiling a plethora of utility functions by integrating them into services

In my Angular 7 multi-module application, I have a utility namespace structured as follows: export namespace Utils { export function util1 (arg: type) { } export function util2 (arg: type) { } ... } Some of these functions are used in templ ...

Disable the loader for a specific method that was implemented in the Interceptor

Custom Loader Interceptor A loader has been implemented within an Interceptor. I have a specific requirement where the loader should not be triggered during the upload() function. It should not be applied to that particular method only. ...

Animations in Angular fail to operate within mat-tabs after switching back when custom components are being utilized

I am facing a similar issue as Olafvv with my angular 16 project. The problem occurs in a mat-tab-group where the :enter animations do not work when navigating away from a tab and then returning to it. However, in my case, the issue lies within a custom su ...