Angular 6: HttpClient Get JSON File 404 Error

≯℡__Kan透↙ 提交于 2019-11-28 10:04:28

问题


Using the HTTP Client, I'm to retrieve a JSON file which resides the assets directory within my Angular 6 App which was generated using the CLI. While I know there are a couple related questions (and answers) related to this topic, but none have worked in my case.

Below is my file structure:

Specifically I'm trying to retrieve us-all-all.geo.json

angular.json

 "projects": {
    "ng-ngrx-highcharts-example": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ng-ngrx-highcharts-example",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src",
              "src/assets",
              "src/favicon.ico",
              "src/assets/us-all-all.geo.json"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },

map-data.service.ts

import { Injectable } from '@angular/core';
import { Observable, of, from } from 'rxjs';
import * as $ from 'jquery';
import { $q } from '@uirouter/angular';

import { catchError, map, tap } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

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

  mapData: any;

  mapDataObservable: Observable<any>;

  constructor(private http: HttpClient) {
  }

  retrieveNationalMapData(): Observable<any> {
    return this.http.get('./assets/us-all-all.geo.json');

  }
  retrieveNationalCountyMapDataAssets(): Observable<any> {
    return this.http.get('assets/us-all-all.geo.json');
  }

  retrieveNationalCountyMapDataLocalHost(): Observable<any> {
    return this.http.get('http://localhost:4200/assets/us-all-all.geo.json');
  }
}

I call the retrieve function in my component

highchart-map.component.ts

$q.all([
      this.mapDataService.retrieveNationalMapData().subscribe((nationalMapData) => {
        console.log(nationalMapData);
        mapData.national = nationalMapData;
      }),
      this.mapDataService.retrieveNationalCountyMapDataAssets().subscribe((nationalCountyMapData) => {
        console.log(nationalCountyMapData);
        mapData.national = nationalCountyMapData;
      }),
       this.mapDataService.retrieveNationalCountyMapDataLocalHost().subscribe((nationalCountyMapData) => {
        console.log(nationalCountyMapData);
        mapData.national = nationalCountyMapData;
      })

Unfortunately when the app loads I see the following:

So at this point I'm not sure what url I should be using to retrieve the JSON.

EDIT

Link to project of GitHub:ng-ngrx-highcharts-example

Should I be trying retrieve the JSON from the Dist directory?

I see that the JSON files located in src/assets folder are stored in the dist/assets when the app is built.

Final Edit

As stated by user184994, the issue was my use of the HttpClientInMemoryWebApiModule which is intercepting any and all HTTP calls. As a result, I was unable to retrieve my JSON files. After I commented out HttpClientInMemoryWebApiModule my gets were working fine, although it breaks my app which utilizes the inMemoryApi


回答1:


The reason is because your app.module is importing HttpClientInMemoryWebApiModule, which intercepts any HTTP calls. Instead of trying to get the JSON from your project, it is instead trying to get it from the InMemoryDataService.

If you remove this import, it should solve the error, although any calls you have that rely on that module will then fail (such as the school, and national requests).




回答2:


That's because you have not defining your path properly since you are in the service folder so you need to change your path {../ which means one step behind}

export class MapDataService {

  mapData: any;

  mapDataObservable: Observable<any>;

  constructor(private http: HttpClient) {
  }

  retrieveNationalMapData(): Observable<any> {
    return this.http.get('../../assets/us-all-all.geo.json');

  }
  retrieveNationalCountyMapDataAssets(): Observable<any> {
    return this.http.get('../../assets/us-all-all.geo.json');
  }

}



回答3:


Several notes...

After running the server, just do a simple thing: copy/paste your resource URL into the browser, like this:

If you see the JSON then everything is fine, it means the problem is with how it is requesting from the Angular app. To understand the issue open Network section (or console) in your browser, most probably the issue is that how you are requesting the file.

For example, this: this.http.get('http://localhost:4200/assets/us-all-all.geo.json');
will most probably be converted to:
http://localhost:4200/http://localhost:4200/assets/us-all-all.geo.json'.

See my point?

Solution is simply to call the resource without http://localshost:4200,
like:
this.http.get('assets/us-all-all.geo.json');



来源:https://stackoverflow.com/questions/50974020/angular-6-httpclient-get-json-file-404-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!