Angular 6: HttpClient Get JSON File 404 Error

后端 未结 3 825
你的背包
你的背包 2020-12-21 07:32

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 t

相关标签:
3条回答
  • 2020-12-21 07:58

    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).

    0 讨论(0)
  • 2020-12-21 08:01

    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');
      }
    
    }
    
    0 讨论(0)
  • 2020-12-21 08:02

    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');

    0 讨论(0)
提交回复
热议问题