gpt4 book ai didi

json - 在没有 HTTP 请求的情况下加载 JSON

转载 作者:太空狗 更新时间:2023-10-29 18:16:00 26 4
gpt4 key购买 nike

我正在使用 Angular 4、NPM、Node.js 和 Angular CLI 开发一个项目。

我有一个非常不寻常的需求,即在没有 HTTP 请求的情况下将 JSON 加载到 Angular 服务中(使用 @Injectable),即它总是作为包的一部分在本地加载,而不是检索来自服务器。

到目前为止我发现的所有内容都表明您要么必须修改项目的 typings.d.ts 文件,要么使用 HTTP 请求从 /assets 中检索它> 文件夹或类似文件夹,这两个都不适合我。

我想要完成的是这个。给定以下目录结构:

/app
/services
/my-service
/my.service.ts
/myJson.json

我需要使用 @Injectablemy.service.ts 服务来加载 JSON 文件 myJson.json。对于我的特殊情况,my.service.ts 文件旁边将有多个 JSON 文件,所有这些文件都需要加载。

澄清一下,以下方法对我不起作用:

使用 HTTP 服务从 Assets 加载 JSON 文件

网址:https://stackoverflow.com/a/43759870/1096637

摘录:

// Get users from the API
return this.http.get('assets/ordersummary.json')//, options)
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);

修改 typings.d.ts 以允许加载 JSON 文件

网址:https://hackernoon.com/import-json-into-typescript-8d465beded79

摘录:

解决方案:使用通配符模块名称在 TypeScript 2+ 版本中,我们可以在模块名称中使用通配符。在您的 TS 定义文件中,例如typings.d.ts,你可以添加这一行:

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

然后,您的代码就会像魅力一样工作!

// TypeScript
// app.ts
import * as data from './example.json';
const word = (<any>data).name;
console.log(word); // output 'testing'

问题

有没有其他人有任何想法可以在不需要这些方法的情况下将这些文件加载​​到我的服务中?

最佳答案

如果直接调用 json 会出错,但一个简单的解决方法是为所有 json 文件声明类型。

typings.d.ts

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

comp.ts

import * as data from './data.json';

关于json - 在没有 HTTP 请求的情况下加载 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44313054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com