Load json from local file with http.get() in angular 2

前端 未结 7 1148
情歌与酒
情歌与酒 2020-11-29 00:38

I\'m trying to load a local json with http.get() in angular 2. I tried something, that I found here on stack. It looks like this:

this is my app.m

7条回答
  •  醉话见心
    2020-11-29 01:14

    I found that the simplest way to achieve this is by adding the file.json under folder: assets.

    No need to edit: .angular-cli.json

    Service

    @Injectable()
    export class DataService {
      getJsonData(): Promise{
        return this.http.get('http://localhost:4200/assets/data.json').toPromise();
      }
    }
    

    Component

    private data: any[];
    
    constructor(private dataService: DataService) {}
    
    ngOnInit() {
        data = [];
        this.dataService.getJsonData()
          .then( result => {
            console.log('ALL Data: ', result);
            data = result;
          })
          .catch( error => {
            console.log('Error Getting Data: ', error);
          });
      }
    

    Extra:

    Ideally, you only want to have this in a dev environment so to be bulletproof. create a variable on your environment.ts

    export const environment = {
      production: false,
      baseAPIUrl: 'http://localhost:4200/assets/data.json'
    };
    

    Then replace the URL on the http.get for ${environment.baseAPIUrl}

    And the environment.prod.ts can have the production API URL.

    Hope this helps!

提交回复
热议问题