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

Incorporate Sendbird into Angular 6 for seamless communication integration

I recently started delving into the world of angular6 and nodejs. I am eager to integrate sendbird with Angular6, but I'm struggling to find a clear starting point. If anyone has successfully done this before, I would greatly appreciate some guidance ...

Just launched NextJS on Firebase, encountering a 403 Forbidden Error

Recently, I successfully deployed my NextJS app on Firebase Hosting and Firebase Functions. However, upon visiting my website after deployment, I encountered an unexpected page. Screenshot This is how my firebase.json file looks: { "hosting&qu ...

Contrasting behaviors between CURL and http.get when dealing with CORS restrictions

It's really starting to frustrate me: Command line: $ curl -X GET "cloudant/url" --header "Authorization: Basic YWRtaW46cGFzcw==" --header "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" { "response": "OK" } Using Angular 2 ...

Troubleshooting problem with ngb carousel timing interval

I am currently developing a web app for selecting maps in Escape from Tarkov. To enhance the visual appeal of the app, I decided to incorporate an ngb-carousel feature for a smooth animation effect. However, I have encountered a problem where the slides ar ...

Angular 5 interception mechanisms

I have been trying to set up interceptors in my Angular 5 project, but unfortunately they are not working. I injected the interceptor in the file app.module.ts, however, I am still encountering errors. Additionally, I added a console.log statement in the i ...

"Utilize the handle property of a component when interacting with the window.onclick

In my component, I have a property called enableButtons which is set to true when I click on an ion-menu label. However, I want this property to revert to false if I click anywhere else. Here's the code I tried: export class ProfilePage implements OnI ...

Error: The `ngMetadataName` property cannot be accessed because it is undefined or null in Internet Explorer version 10

Encountered an issue in IE 10 that is not present in IE 11: Error: TypeError: Unable to get property 'ngMetadataName' of undefined or null reference The property ngMetadataName can be found in the file vendor.js. This is the content of polyf ...

I'm having trouble establishing a connection with the Appwrite platform

Encountered an issue while trying to connect to appwrite. The specific error message is: Uncaught (in promise) TypeError: Failed to construct 'URL': Invalid URL at Account.<anonymous> (appwrite.js?v=d683b3eb:932:19) at Generator.nex ...

Progressive series of observable conditions

The issue at hand: I am faced with the task of checking multiple conditions, some of which lead to the same outcome. Here is the current flow: First, I check if a form is saved locally If it is saved locally, I display text 1 to the user If not saved l ...

Steer clear of receiving null values from asynchronous requests running in the background

When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly ...

Guide to Angular Interface Styling - Ambiguous Suggestions

After reviewing the Angular style guide for interfaces, I find two recommendations particularly perplexing: The suggestion to use a class instead of an interface for services and declarables (components, directives, and pipes) leaves me puzzled. Similarl ...

Turn off the background graphic in chartjs

Greetings all! I'm currently facing an issue with removing the hashtag background of a line chart. Is there any method to disable or remove it? I am utilizing chartjs in my Ionic 2 app. Your assistance is greatly appreciated. Below is the code for my ...

Exporting SVG to image in Ionic is successful on Android devices, but the image gets cut off when viewed on

I am facing an issue with exporting an SVG as a base64 encoded image and sending it to the server for storage on Google Cloud Storage. The process works fine on Android and in browsers, but fails when attempted on a physical device running IOS. On IOS, t ...

Is it possible to use the provide() method with a string in Angular 2 when writing

I am attempting to utilize a String as a token for providing instead of a class: app.RandomComponent = ng.core .Component({ selector: "randomComponent", template: "Component!", providers: [ ng.core.provide("Stuff", ...

Ways to retrieve a query from a NextApiRequest

Can anyone help me figure out how to retrieve the value of "type" in my http request query? The URL I am working with is http://localhost:3000/api/hello?type=customer. export async function GET(req: NextApiRequest, res: NextApiResponse) { if (req.method != ...

Angular 2 encountering a memory exhaustion issue in the JavaScript heap

I am currently using Angular CLI and would appreciate it if you could verify my CLI information @angular/cli: 1.2.1 node: 6.10.0 os: win32 x64 @angular/animations: 4.1.1 @angular/common: 4.0.0 @angular/compiler: 4.0.0 @angular/compiler-cli: 4.0.0 @angular ...

Problem: Unable to open Angular href links on IOS devices

I am experiencing an issue with a shared-code application in Android and IOS. The link successfully opens on an Android device but fails to open on an IOS device. Are there any differences between the two platforms that could be causing this discrepancy? ...

Getting the date from an XHR header in Angular2: A step-by-step guide

Is it possible to retrieve a date from XHR Header Response? I attempted to include '{observe: 'response'}' as options constructor(private http: HttpClient) { } getAllTemps() { return this.http.get<AllTemp>(this.endp ...

TypeScript perplexed Babel with its unfamiliar syntax and could not compile it

Encountered a problem while attempting to compile typescript. It appears that babel was unable to comprehend the "?." syntax on the line node.current?.contains(event.target) export function useOnClickOutside(node: any, handler: any) { const handlerRef = ...

To update the scopes for Firebase GoogleAuthProvider and remove the email scope, while adding only the youtube.readonly scope,

After experimenting with Firebase and Angular 2, I have managed to implement user validation in my app and retrieve YouTube Channel information. Below is the code snippet I am using: return new Promise((resolve, reject) => { let provider = new ...