Struggling to retrieve local JSON file in Angular 5 - facing relentless 404 error

I've scoured every available article and post on this topic, yet I am still unable to pinpoint where I am making a mistake with this seemingly simple task. (Particularly, following this example.) It seems like I am missing something obvious, but after staring at this for so long, I just can't see it.

I have a JSON file named isRecognized.json in the assets/mockData directory. I've made sure to add the mockData directory to my webpack configuration file so that it is included in the /dist directory. If I navigate to http:localhost:4200/assets/mockData/isRecognized.json, I am able to view the file, confirming its availability.

However, every attempt to retrieve the file using HTTP Client results in a 404 error, regardless of my approach.

EDIT: I am utilizing Webpack, not Angular CLI.

app.component.ts

import { MyService } from './services/my.service';
import { Component, OnInit, Renderer2 } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

/*
* Main app component that houses all views.
*/
@Component({
    selector: 'app-comp',
    templateUrl: './app.component.html'
})

export class AppComponent implements OnInit {

    constructor(
        private route: ActivatedRoute, private service: MyService
    ) {}

    ngOnInit() {
      this.service.isRecognized();
    }

}

my.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class MyService {

  constructor(private http: HttpClient) { }

  isRecognized() {
    this.getJSON('isRecognized').subscribe(data => {
      console.log(data);
    });
  }

  getJSON(fileName): Observable<any> {
    return this.http.get('http://localhost:4200/assets/mockData/' + fileName + '.json');
  }
}

The error displayed in the browser console is:

AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: [object Object]
    at viewWrappedDebugError (core.js:9795)
    at callWithDebugContext (core.js:15101)
    at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.js:14628)
    at ViewRef_.webpackJsonp../node_modules/@angular/core/esm5/core.js.ViewRef_.detectChanges (core.js:11605)
    at core.js:5913
    at Array.forEach (<anonymous>)
    at ApplicationRef.webpackJsonp../node_modules/@angular/core/esm5/core.js.ApplicationRef.tick (core.js:5913)
    at core.js:5746
    at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
    at Object.onInvoke (core.js:4756)

Upon debugging the error, the body of the error message appears as follows: https://i.sstatic.net/stVLw.png

Answer №1

I've managed to successfully implement this feature in my application by simply using a URL structure like the one below:

private productUrl = 'api/products/products.json';

It's worth noting that the path does not include the localhost part.

Instead, consider using a structure similar to this:

'assets/mockData/' + fileName + '.json'

Additionally, make sure that the path is included under 'assets' in your angular.json file:

        "assets": [
          "src/favicon.ico",
          "src/assets",
          "src/api"
        ],

IMPORTANT: I didn't make any modifications to my webpack configuration. (Although I am using the CLI.)

If you're interested in checking out some functional code that accesses a JSON file, I have provided an example here:

https://stackblitz.com/edit/github-gettingstarted-deborahk

Answer №2

To improve efficiency, I recommend setting up a subscription within the component and having the service return an Observable:

Service:

@Injectable()
export class MyService {

  constructor(private http: HttpClient) { }

  isRecognized(fileName): Observable<any> {
    return this.http.get('http://localhost:4200/assets/mockData/' + fileName + '.json');
  }

}

Component:

export class AppComponent implements OnInit {

    constructor(
        private route: ActivatedRoute, private service: MyService
    ) {}

    ngOnInit() {
      this.service.isRecognized(fileName)
         .subscribe(data => {
              console.log(data);
         });
    }
}

Answer №3

Although this approach may not directly solve the unique problem you're facing, consider exploring the npm package json-server. I find it helpful for simulating the API during client development and testing.

Check out json-server on npm

With json-server, you can easily set up a node web server on port 3000, making it a straightforward tool to use right from the start.

Take a look at this tutorial for an example of how it can be utilized: Implementing mock APIs with json-server

While there may be more advanced examples available and setting up the proxy may not always be required, it should suffice for your needs.

Answer №4

After some thorough investigation, I have finally uncovered the solution! It turns out that the culprit was an import statement in my app.module.ts file:

InMemoryWebApiModule.forRoot(InMemoryDataService, { dataEncapsulation: false })

Simply removing this import swiftly resolved the problem at hand.

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

Having difficulty creating a custom user registration field in Services 3.0 for Drupal

On attempting to submit data to my custom zip code field on the user registration form, I encounter the following issue: Sending post data to endpoint/user/register.json { "name":"testuser123", "pass":"testuser123", "mail":"<a href="/cdn-cgi/l/email-p ...

Transforming ogg file formats in Angular for compatibility with Safari browsers

In order to play an audio file in Safari browser with the format audio/ogg; codecs=opus, our server's limitations prevent the conversion to formats supported by Safari (caf-opus/wav/mp3). We are seeking a solution to convert ogg files to Safari-compa ...

Tips for setting up nextjs with typescript to utilize sass and nextjs font styles

I am attempting to configure a Next.js TypeScript app to work with Sass and a font in Next.js. I have been following the steps outlined in this article. Without the font module, styles are working correctly. Below is my next.config.js without the font co ...

Determining the parameter type of an overloaded callback: A comprehensive guide

I am currently working on creating a type-safe callback function in TypeScript with a Node.js style. My goal is to define the err parameter as an Error if it exists, or the data parameter as T if not. When I utilize the following code: export interface S ...

What is the process for uploading a JSON file from your local drive?

I am attempting to use jQuery to load a local JSON file. The code seems to be functioning properly, but for some reason, the data is not being made available in an array. $.getJSON("/ajax/data/myjasonfile.json", function(json) { console.log(js ...

What is the best way to include optional parameters in a RESTful API?

I'm currently utilizing the REST API found at this link. Here is an example code snippet for reference: server = "https://rest.ensembl.org" ext = "/vep/human/hgvs/ENSP00000401091.1:p.Tyr124Cys?" r = requests.get(server+ext, header ...

After executing grunt serve, Bower issues a warning for jquery stating "not injected"

Recently, I had to clone a project and rebuild bower packages. It seems that jQuery has been updated, causing a warning to appear: Warning: Please check the "app/bower_components/jquery" folder for the necessary file and manually include it in your ...

Material Modules are causing issues with AOT compilation

I'm encountering multiple errors that all share a similar pattern: ERROR in ./node_modules/@angular/material/button/typings/index.ngfactory.js Module build failed: Error: Invalid name: "@angular/material/button" at ensureValidName (C:\path&b ...

Store a JSON object in a file on your smartphone

I am working on a project where I need to download JSON data from a server and then save it to a file on an Android mobile device. I am currently looking into using external storage for this purpose. I also need the ability to search for specific data wit ...

Disable editing of all form controls within a template-based form

We are looking to implement a 'read-only' feature for certain users in our template-based form that utilizes Angular Material controls such as matInput and mat-select. My initial approach was to check user privileges and then iterate through the ...

Nested MD-list-item in Angular 2 Material

Trying to implement nested lists in a sidenav using Angular 2 with material design. Here is the initial code: <md-sidenav #sidenav class="sidenav" mode="over" opened> <md-nav-list> <md-card class="user-card"> ...

Navigable outside graphic key in AmCharts version 4

Is it possible to achieve a scrollable legend in AmCharts 4 similar to this AmCharts 3 tutorial? With the absence of legend.divId in AmCharts 4, controlling legend size seems challenging as it is all rendered as a single SVG element with limited control us ...

NativeScript does not acknowledge the permission "android.Manifest.permission.READ_CONTACTS"

Hi there! I am a beginner in mobile development and currently learning Angular 2. I am facing an issue with requesting permission for reading contacts in NativeScript. It seems that "android" is not being recognized. For instance, when trying to execute t ...

Sending the wrong callback response in a Volley request callback

I recently encountered a strange issue while using Volley for making requests in my Android app. I added a callback to handle the response, but when I initiated two requests from different activities, the second request was returning the response of the fi ...

Steps to Export Several Fusion Charts into Individual Image Files

My webpage contains multiple charts created using the Fusion Chart library. There are three different charts on the page, and I want to export each chart as a separate PNG file. However, when I click the export button, it generates separate images of the ...

Convert JSON string to a C# list for a dropdownlist

I am working on a Windows Form application where I need to deserialize a JSON string obtained from a web address in order to extract two specific values. Can someone guide me on how to achieve this? Here is the code snippet I have for fetching the JSON st ...

Assessing functionality in Angular8 by testing a function that accesses an array from a service

I have a function that I want to test along with the current test setup: canShowIt() { let showit = false; const profils = this.requestsService.userProfil; showit = profils.some((profil) => profil.id === this.profileDetail.id); return showit; ...

Is JsonEditor capable of editing JSON Schemas effectively?

For a while now, I have been impressed by the functionality of JSON-editor and have been using it to edit documents based on a specific JSON schema. But why stop there? Many users utilize JSON-Editor to make changes to JSON documents according to the corr ...

Blank webpage caused by ngx TranslateService

Every time I attempt to translate Angular components using ngx-translate/core by utilizing the translateService in the constructor, the page appears blank. This is my appModule : import { NgModule } from '@angular/core'; import { BrowserModule } ...

Utilizing Twitter search queries to generate JSONArray in an Android application

Greetings, this is my debut post here. I'm currently working on an app that searches and retrieves #tag tweets related to my activities. While I have succeeded in fetching tweets from a user using "1.1/statuses/user_timeline.json?screen_name", I encou ...