在本地项目文件夹中加载JSON时使用angular 2 http offline [英] Using angular 2 http offline when loading JSON in local project folder

查看:165
本文介绍了在本地项目文件夹中加载JSON时使用angular 2 http offline的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用http get方法加载Angular 2项目文件夹中的本地json文件。请查看以下示例代码段:

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

现在,当我尝试通过互联网加载它时,它正在运行。但是当我从浏览器开发者选项中找到离线复选框时( https://developers.google.com/web/tools/chrome-devtools/network-performance/reference#offline ),json再次停止加载。它开始在控制台中显示关于没有互联网连接的错误,并且没有加载任何内容。

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.

还有其他方法吗?或使用http get..how来做?

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

推荐答案

你可以导入 json 文件,如果你这样做:

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

创建一个json-typings.d.ts文件:

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

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

这是通配符模块定义,允许我们在这种情况下导入非javascript文件JSON文件。

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

您现在应该能够将json文件导入您的项目:

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

import * as products from "./products.json";

这篇关于在本地项目文件夹中加载JSON时使用angular 2 http offline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆