Using angular 2 http offline when loading JSON in

2020-07-13 07:34发布

问题:

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?

回答1:

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";