Import JSON data into Angular 2 Component

After much effort, I have finally figured out how to load JSON data into an Angular 2 Component.

datoer.service.ts:

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

@Injectable()
export class DatoService { 

    dato: Array<any>;

    constructor(private http: Http) {}

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

kalender.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 valgteSkoleRuter: Array<any>= [];

    constructor(private valgteSkolerService: ValgteSkolerService, private DatoService: DatoService) {
        this.datoer = this.DatoService.getDato();
    }

    ngOnInit() {
      this.valgteSkolerService.hentLagretData();
      this.valgteSkoleRuter = this.valgteSkolerService.delteValgteSkoleRuter;
    }

My template looks like this:

<p *ngFor="let dato of datoer"> {{dato}} </p>

The issue arises with "this.datoer" in the component. It shows an error stating that it does not exist on type KalenderComponent. I attempted to declare it in the component as follows:

private datoer: Array<any> = [];

However, another error popped up saying, "Type 'Observable' is not assignable to type 'any[]'. Property 'length' is missing in type 'Observable'."

Do you have any suggestions on how to resolve this?

Answer â„–1

When using the http service in Angular 2, as stated in the Angular2 Http class documentation, it returns an observable instead of an array with results. This is because the data is fetched asynchronously. To access the data, you need to subscribe to the observable and handle the notifications generated when the http request is completed.

Here's an example:

public dates: any[] = [];    
constructor(
    private selectedSchoolsService: SelectedSchoolsService,
    private DateService: DateService) {

    this.DateService
        .getDate()
        .subscribe(dates => { this.dates = dates; });    
}

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

Utilize Primeng data grid to calculate total sum and display it in the footer section

I have been utilizing primeng datatable in a recent project and am currently facing an issue with calculating the sum in the footer of a row grouping DataTable. The summation needs to occur while data is being edited and new data is being entered. Below i ...

Output JSON in PHP with key-value pair

Why is this code not functioning as expected? What mistake have I made? $json = json_encode($myInstance->getData($id)); $result = json_decode($json,true); $i = 0; foreach ($result as $value) { echo '<div>'.$value[$i] ...

Angular Dialog Component: Passing and Populating an Array with Mat-Dialog

Here's the situation: I will enter a value in the QTY text field. A Mat dialog will appear, showing how many quantities I have entered. My question is, how can I iterate an object or data in the afterclosed function and populate it to the setItem? Cur ...

Implicated Generic in TypeScript

Is there a way to simplify my class A implementation? export class A<TB extends B<TC>, TC> implements TD<TB, TC> { make(): TC {} } Currently, I have to specify the TC type every time I create an instance of A: class CTest {} class BTes ...

Learn how to extract precise information from a JSON array by utilizing Angular 6

After making a GET request in Angular 6, I successfully retrieved data from a JSON array. Now, I have this JSON data as an example and my goal is to find the team(s) that employee "TEST4KRWN" is part of. Can anyone guide me on how to write a JSON query us ...

Tips for associating an id with PrimeNg menu command

Within my table, I have a list of items that I would like to enhance using PrimeNg Menu for dropdown menu options. The goal is to enable navigation to other pages based on the selected item id. When a user clicks on a menu item, I want to bind the id of th ...

Developing an Observer and sending updates to my followers

I have a function that returns an Observer for subscription. Inside this function, I make an API call which also returns an Observer to which I subscribe. Once I analyze the data received from this Observer, I need to notify my own Observer subscribers. B ...

Tips for transforming json data into a more readable format for humans

This is my JSON data. initiated with options {'record_id': 335, 'backup_config_id': 28, 'attachement_type': 3, 'instance_id': 48, 'volumes': [{'aws_instance_id': 'xyz', 'aws_instan ...

Fetching json data from the request in Node.js

I'm currently working on a project that involves using the request module to send an HTTP GET request to a specific URL in order to receive a JSON response. However, I've run into an issue where my function is not properly returning the body of ...

Display a set of JSON objects on separate lines rather than consolidating them on a single line

When I load a json file and attempt to extract certain values, the output is displayed all on one line. Here is an example of the current output: {"time":"1:2:2","post":"1","user":"4","text":"Masaru Emoto"}{"time":"1:3:8","post":"8","user":"5","text":"Me ...

Can you explain the concept of static in Typescript?

Exploring the distinctions between the static and instance sides of classes is addressed in the Typescript documentation on this page. The static and instance sides of classes: understanding the difference In object-oriented programming languages like ...

The ambiguity surrounding the timing of decorator invocation in TypeScript

My understanding was that decorators in TypeScript are invoked after the constructor of a class. However, I recently learned otherwise. For example, the primary response on this thread suggests that Decorators are called when the class is declared—not wh ...

Retrieve the product IDs by selecting the checkboxes, then compile a fresh array consisting of the identified IDs

I am currently delving into the realm of typescript/angular2+ as a fledgling student, and I have taken on the task of creating a website to put my newfound knowledge to the test. The view is up and running, but I'm facing some roadblocks as I work on ...

Is it possible to obtain the Apache server status (mod_status) output in JSON or XML format?

Exploring Apache's "mod_status" Feature: One of the functionalities provided by Apache is the "mod_status", which allows users to monitor the current status of their server. When accessed, it presents a wealth of information similar to the sample pag ...

The property is not found within the type, yet the property does indeed exist

I'm baffled by the error being thrown by TypeScript interface SendMessageAction { type: 1; } interface DeleteMessageAction { type: 2; idBlock:string; } type ChatActionTypes = SendMessageAction | DeleteMessageAction; const CounterReduc ...

Encounter the "Error: Source 'cloudsTileLayer-RasterSource' not found" message while trying to integrate a weather tile layer into Azure Maps

I have been working on a React application that utilizes the React-Azure-Maps npm package. My current challenge involves creating a weather layer, which I believe shares similarities with the sample code provided for layers. The code snippet responsible f ...

How can one utilize JSON.parse directly within an HTML file in a Typescript/Angular environment, or alternatively, how to access JSON fields

Unable to find the answer I was looking for, I have decided to pose this question. In order to prevent duplicates in a map, I had to stringify the map key. However, I now need to extract and style the key's fields in an HTML file. Is there a solution ...

Choose the initial mat-option with mat-select functionality

In my app, I have several Angular Material select dropdowns with mat-options that are updated reactively based on other values (filtering of options). Here's an example: <mat-select #selects (selectionChange)='formChanges()' [placeholder ...

Utilizing JQuery Template to Invoke JavaScript Functions

If I have the following JSON object structure: ITEMS is an array with one element, and FILTER is another array with 3 items in it. Description: "churches with some restrictions" ITEMS: {...} [0]: {...} FILTER: {...} ...

Transferring information between components within AngularJS

export class AppComponent { title = 'shopping-cart'; ngOnInit() { } images = [ { title: 'At the beach', url: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?ixlib=rb-4.0.3&ixid=MnwxMjA ...