Search code examples
jsonangularhttpmodels

Cant fetch data from local json using Angular


I am trying to fetch data from a local json file so that i would manipulate the data in the view (if u choose UnitOne the only 'roles' u can pick are 'role1','role2','role3' etc.)
So i build a sample application just to demonstrate the whole deal. Basically I'm getting this error message:

Error: Uncaught (in promise): SyntaxError: Unexpected token < in JSON at position 0 SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at Response.Body.json

here's the code Link


Solution

  • Your http call is not getting the JSON file because it does not live at http://localhost/data.json. That call is returning some HTML, which is why you get the error you get.

    You can import the JSON file using TypeScript instead of trying to request it via HTTP.

    import { Component, OnInit } from '@angular/core';
    import 'rxjs/add/operator/toPromise';
    import { Http } from '@angular/http';
    import { RootObject, Parameter, Infos, Info, ValidValues, Condition} from './data.model';
    
    import json from './data.json'
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      data: RootObject;
      print: string = '';
      constructor(private http: Http) { }
    
      ngOnInit() {
        this.data = json as RootObject;
        this.print = this.data.parameters[1].keyParameterName;
      }
    }
    

    Here is a working version.

    There may be prettier ways to write the code, but I'll leave that up to you. :)


    If you absolutely must request the JSON via HTTP, then I recommend you place it in your assets directory and make a call to /assets/data.json instead. That might work. Either that or use a CDN/external URL to request it from. But keep in mind you would need to have CORS enabled on that server or your request will be blocked by your browser.