Issue encountered when working with interface and Observable during the http parsing process

Visual Studio File Structure Error

app(folder)
  -->employee-list(folder)
       -->employee-list.component.html
       -->employee-list.component.ts
  -->app.component.html
  -->app.component.ts
  -->app.module.ts

  -->employee.json
  -->employee.service.ts
  -->employee.ts

In this case, all the files are at the same level and I'm trying to pass data from employee.json to the employee component using the HTTP get method. However, an error is being triggered.

Error
message: "Http failure during parsing for " name: "HttpErrorResponse", error:Object

employee.json

[
  {"id":2,"name":"Shiva","age":23},
  {"id":3,"name":"ABC","age":25},
]

employee.ts

export interface Employee {
  id:number,
  name:string,
  age:number,
}

employee.service.ts

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Employee} from './employee';
import {Observable} from 'rxjs';

@Injectable()
export class EmployeeService {
public _url:string="./employee.json";
  constructor(private http:HttpClient) { }

  getEmp(): Observable<Employee[]>{
    return this.http.get<Employee[]>(this._url);
  }
}

employee-list.component.ts

import { Component, OnInit } from '@angular/core';
import {EmployeeService} from '../employee.service';

@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
 public employee=[];
 constructor(private _employeeService:EmployeeService) { }

  ngOnInit() {
    this._employeeService.getEmp()
        .subscribe(data => this.employee = data);
  }
}

For more information, visit https://stackblitz.com/edit/htpgeterror

Answer №1

To ensure proper access for the Angular service, it is recommended to store your employee.json file within the assets folder.

Organizational Structure

app(folder)
  --> assets (folder)
        --> data (folder)
              --> employee.json // contains employee data 

service.ts

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Employee} from './employee';
import {Observable} from 'rxjs';

@Injectable()
export class EmployeeService {
public _url:string="assets/data/employee.json";
  constructor(private http:HttpClient) { }

  getEmp(): Observable<Employee[]>{
    return this.http.get<Employee[]>(this._url);
  }

}

Check out the modified solution on stackblitz

We hope this information proves helpful!

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

Querying the api for data using Angular when paginating the table

Currently, I have a table that retrieves data from an API URL, and the data is paginated by default on the server. My goal is to fetch new data when clicking on pages 2, 3, etc., returning the corresponding page's data from the server. I am using an ...

There was an error encountered during the npm install process

C:\Users\Mayur Saner\pmrm>npm install npm ERR! code ENOTFOUND npm ERR! errno ENOTFOUND npm ERR! network request to http://registry.npmjs.org/@fortawesome%2ffontawesome-free failed, reason: getaddrinfo ENOTFOUND proxy.company.com npm ERR! ...

What causes React component state initialization to return a `never` type when set to null?

Initializing a component's state to null outside of the constructor results in the state having the type never in the render function. However, when the state is initialized within the constructor, the correct type is maintained. Despite many StackO ...

I'm getting errors from TypeScript when trying to use pnpm - what's going

I've been facing an issue while attempting to transition from yarn to pnpm. I haven't experimented with changing the hoisting settings yet, as I'd prefer not to do so if possible. The problem lies in my lack of understanding about why this m ...

How to detach functions in JavaScript while preserving their context?

Can functions in JavaScript be detached while still retaining access to their context? For instance, let's say we have an instance of ViewportScroller called vc. We can retrieve the current scroll position with the following method: vc.getScrollPosi ...

The validator is incorrectly diagnosing the input as 'invalid' when in reality it is not

Currently, I am working on creating a text field that must not be empty and should also not start with a specific set of characters (let's say 'test'). For example, I want testxyz or an empty field to be considered invalid, while anything e ...

Angular application navigation does not work as expected when the application is served in Express.js

I have an Angular 7 application that is running on an ExpressJS server. This is how the server part of the app is set up: app.get('/', (req, res) => { console.log(`sending...`); res.sendFile(path.join(__dirname, 'index.html') ...

Is it possible for the link parameters array in Angular2 Routing to contain more than one element?

Currently delving into Angular2 on my own. According to the text I'm studying, when a user navigates to a feature linked to a route using the routerLink directive, the router employs both the link parameters array and the route configuration to constr ...

A guide to implementing vue-i18n in Vue class components

Take a look at this code snippet: import Vue from 'vue' import Component from 'vue-class-component' @Component export default class SomeComponent extends Vue { public someText = this.$t('some.key') } An error is being thr ...

What is the best way to reorganize an object's properties?

Looking for a way to rearrange the properties of an existing object? Here's an example: user = { 'a': 0, 'b': 1, 'c': 3, 'd': 4 } In this case, we want to rearrange it to look like this: user = { &a ...

Unable to navigate to partial view within MEAN application

I'm currently following a tutorial on creating single page applications using the MEAN stack. So far, I have successfully rendered the index.jade view. However, I encountered an issue when trying to route to a partial view as the DOM of the page does ...

Encountering issues with MyModel.findOne not being recognized as a function while utilizing Mongoose within Next.js 14 Middleware

Within my Next.js middleware, I am encountering the following code: let user: UserType[] | null = null; try { user = await findUser({id}); console.log("user", user); } catch (error: any) { throw new Error(error) ...

The issue of excessive recursion in Typescript

Currently, I am in the process of learning Typescript while working on some exercises. While attempting to solve a particular problem, I encountered an error related to excessive recursion. This issue arises even though I created wrapper functions. About ...

The parameters in VueJS are malfunctioning on this webpage

I created my vue in an external file and included it at the bottom of my webpage, but I am encountering issues with its functionality. One specific problem arises when using v-model, resulting in a template error displayed on the page: Error compiling t ...

Create a function that retrieves the value associated with a specific path within an object

I want to implement a basic utility function that can extract a specific path from an object like the following: interface Human { address: { city: { name: string; } } } const human: Human = { address: { city: { name: "Town"}}}; getIn< ...

Syncing data between local storage and a remote server using Ionic5 provider

I've been considering implementing a data provider that could store a duplicate of the backend data locally for quick access. I believe this concept is referred to as mirroring or something similar. Nevertheless, it must be synchronized and updated r ...

The Angular compiler encounters an error when working with jsonwebtoken

Having some trouble with adding jsonwebtoken to my code. VS Code seems to think the code is fine, but the compiler keeps failing Any ideas on why this might be happening? Thanks for any help! Here's a snippet of my code: this.http .po ...

Error 414: The URL exceeds the maximum length and cannot be processed

I am currently utilizing vuejs and sending an axios request to the server in order to download a csv file. download() { var that = this //this.records = [{id: 1, name: 'Jack'}, {id: 2, name: 'Jacky'}, {id: 3, name: &apos ...

Even if I set a small modal, the large one can still be visible in the background

I've been working on a small modal, but encountered an issue where the large modal remains visible in the background when the small one is displayed. Any suggestions on how to fix this? I made some updates to my code based on recommendations. Here is ...

What is the best way to ensure TypeScript recognizes a variable as a specific type throughout the code?

Due to compatibility issues with Internet Explorer, I find myself needing to create a custom Error that must be validated using the constructor. customError instanceof CustomError; // false customError.constructor === CustomError; // true But how can I m ...