Obtaining JSON data in an Angular service: A beginner's guide

My JSON file has the following structure:

{
 "user": [
    {
      "id": 0,
      "data": [
        {
          "userName": "iheb",
          "useremail": "",
          "userPassword": "kkk"
        }
      ],
      "questionnaireListe": [
        {
          "questionnaire": [
            {
              "id": 2,
              "section": [
                {
                  "sectionName": "produit 1",
                  "question": [
                    {
                      "questionName": "question 1",
                      "answer": [
                        {
                          "answerName": "reponse 1"
                        }
                      ]
                    }
                  ]
                },
                {
                  "sectionName": "produit 2",
                  "question": [
                    {
                      "questionName": "question 2",
                      "answer": [
                        {
                          "answerName": "reponse 1"
                        },
                        {
                          "answerName": "reponse 2"
                        }
                      ]
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
}

I have a service that includes a function to fetch data from this JSON file:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';


@Injectable({
  providedIn: 'root'
})
export class QuestionnaireService {

  constructor(private _Http:HttpClient) { } 
  getUser() {
    return this._Http.get("http://localhost:3000/user");
  }
}

In addition, I have a component.ts file structured like this:

import { Component, OnInit } from '@angular/core';
import { QuestionnaireService } from '../questionnaire.service';
...

// Content of UserComponent and respective functions here
...

Lastly, there is a separate service defined as follows:

import { Injectable, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { QuestionnaireService } from './questionnaire.service';
...

// Content of AuthUserService including login logic here
...

Despite using the same method in both the component and service files, the service throws an error:

ERROR TypeError: Cannot read property 'data' of undefined

If you can identify why the function works in the component but not in the service, any assistance would be greatly appreciated.

Answer №1

This issue arises from attempting to access the user object within the service before it has been properly initialized. One solution is to define a class that represents the user object with default values for its data and other attributes. Then, instantiate an instance of this class to serve as the user object.

class UserModel {
 id: number;
 data = [];
 questionnaireListe = [];

}

Next, ensure that the user property inside the AuthUserService is declared as type UserModel.

user: UserModel = new UserModel();

Answer №2

Have you created the command to view the JSON using npm install -g json-server

json-server --watch src/data/name.json --port 3000

You might have overlooked specifying the object's model

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

Pressing a button triggers the highlighting of a tab in HTML through the use of Javascript

In the corner of my webpage, I have three tabs: info, question, order. When I click on one tab header, only that tab should highlight. The info section includes two buttons that link to the question and order tabs. When these buttons are pressed, the respe ...

Angular 6 application experiencing an issue where the browser console is not displaying an error that says "Cannot GET /

I was tasked with making modifications to an Angular 6 web application, which I hadn't worked on before. After receiving the source code, I attempted to display the website but encountered errors. I spent late nights and early mornings trying to succe ...

Display array elements in a PDF document using pdfmake

Upon reaching the final page of my Angular project, I have an array filled with data retrieved from a database. How can I utilize pdfmake to import this data into a PDF file? My goal is to display a table where the first column shows interv.code and the ...

Fatal error in view binding crashes entire Angular 2 application

Within my template, there is an expression that is causing an exception: <h1>Foo: {{model.somebodyForgotToInitializeMe.foo}}</h1> When this error occurs, the model produces the following message on the console: Uncaught EXCEPTION: TypeError: ...

Determining the type of <this> in an Object extension method using TypeScript

I am attempting to incorporate a functionality similar to the let scope function found in Kotlin into TypeScript. My current strategy involves using declaration merging with the Object interface. While this approach generally works, I find myself missing ...

What is the best way to implement persistStore in Redux-Toolkit?

Here is my setup: import AsyncStorage from '@react-native-async-storage/async-storage' import { persistStore, persistReducer } from 'redux-persist'; import { configureStore } from "@reduxjs/toolkit"; import { searchReducer } f ...

Exploring search filters using KnockoutJS

I'm currently working on incorporating a search filter into my web application. After reading some informative articles and exploring various Jsfiddles, I've attempted to enable searching by TypeName to display the corresponding row with that spe ...

What's the rationale behind receiving the second before the first?

I've been digging into ES6 promises, and I thought I had a handle on it for a moment. However, it seems like I may have hit a roadblock. What I'm aiming to do is handle a series of file operations where each operation depends on the completion o ...

Unable to compile the product

Hello there! I am currently working on preparing a build to launch my app in the play store. I have attempted to create a product build, and in my main.ts file, I added the following line of code: import { platformBrowserDynamic } from '@angular/plat ...

When trying to upload a file with ng-upload in Angular, the error 'TypeError: Cannot read properties of undefined (reading 'memes')' is encountered

Struggling with an issue for quite some time now. Attempting to upload an image using ng-upload in angular, successfully saving the file in the database, but encountering a 'Cannot read properties of undefined' error once the upload queue is comp ...

Identifying specific text enclosed within tags in an external file using PHP

I recently started learning about php, and I am looking for a script that can identify text between specific tags in an external file. I came across a solution here that extracts the text within tags from a given string. However, I am unsure how to mo ...

JavaScript function overriding allows a subclass to provide a specific implementation of

I have a JavaScript file with two methods: var DBProcessing = function() { console.log("ok") ... } var DBProcessing = function(str) { console.log(str); ... } When calling DBProcessing(), I am only getting an output of undefined. Is there a way to expli ...

Achieve a fading effect on an element as you scroll down the page

I successfully implemented a toggle audio button on my website, but now I would like it to fade in along with the scroll-to-top button that I also have (which operates similarly to the buttons on scrolltotop.com). Is there a simple way to achieve this? He ...

Execute a virtual mouse click on a button without the need for a physical click

I'm facing an issue with buttons that have a canvas animation triggered by the react library react-ink. The problem is that this animation only works when the button is clicked using the mouse cursor. However, in my application, I have assigned hotkey ...

Refresh the DOM based on changes in Vuex store state

One of the issues I'm facing is with an 'Add To Basket' button that triggers a Vuex store action: <button @click="addToBasket(item)" > Add To Basket </button> The Vuex store functionality looks like this: const actions = { ...

Unexpected behavior encountered when using the $http.post method

I've been working with a component that I utilized to submit data to the Rest API. The code snippet for the component is as follows: (function(angular) { 'use strict'; angular.module('ComponentRelease', ['ServiceR ...

Unable to display image on HTML page in Sails JS

In my current project, I am utilizing Sails Js and Mongo DB for development. When a user uploads an image and content for a blog post, I store it in the images folder and save the file destination along with the content to MongoDB. My goal is to display bo ...

Creating a custom hook to detect when multiple elements are hovered over

I am currently working on creating a hook that can identify when hover is triggered over specific buttons. Here is what I have so far: enum options { buttonOne: 'buttonOne', buttonTwo: 'buttonTwo' } type HoverType= { [key in opti ...

"By simply pressing the back button, Material UI Table effortlessly expands the row limit to accommodate

After creating a Material UI table and implementing Pagination, I noticed that the row limit increases automatically when clicking the back button. Even after consulting the Material UI docs, it seems like others are facing the same issue. Can anyone provi ...

Mapping Store Fields to JSON Properties in ExtJS: A Complete Guide

I am working with a JSON data object that includes exchange rates information: { "disclaimer": "Exchange rates provided for informational purposes only and do not constitute financial advice of any kind. Although every attempt is made to ensure quality, ...