Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using angular 2 http offline when loading JSON in local project folder

I have been trying loading a local json file present in my project folder of Angular 2 using http get method. Look at the following example code snippet:

private _productURL = 'api/products/products.json';    
getProducts(): Observable<any> {
        return this._http.get(this._productURL).map((response : Response) => <IProduct[]> response.json())
        .do(data =>console.log(JSON.stringify(data))).catch(this.handleError);
    }

Now when I'm trying to load it with internet connected, it's working. But when I'm turing on the offline checkbox from the browser developer options(https://developers.google.com/web/tools/chrome-devtools/network-performance/reference#offline), the json stops loading again. It starts showing me error in console about No internet connection and doesn't load anything.

Is there any other way to do this? or using http get..how to do it?

like image 444
Kush Grover Avatar asked Apr 11 '17 12:04

Kush Grover


People also ask

Does Angular use JSON?

JSON is used by Angular in a variety of contexts, including configuration. For example, the project generated by Angular CLI comprises many files with the . json extension, most notably the package. json and angular.


1 Answers

You can import a json file if you do as follows:

create a json-typings.d.ts file with:

declare module "*.json" {
    const value: any;
    export default value;
}

this is a wildcard module definition that allows us to import non javascript files in this case JSON files.

you should now be able to import json files to your project:

import * as products from "./products.json";
like image 72
Ofer Herman Avatar answered Oct 05 '22 23:10

Ofer Herman