Ste*_*ios 5 json angular2-services angular
我正在使用 Angular 4、NPM、Node.js 和 Angular CLI 进行一个项目。
我需要在@Injectable没有 HTTP 请求的情况下将JSON 加载到 Angular 服务中(使用),即它总是作为包的一部分在本地加载,而不是从服务器检索。
到目前为止,我发现的所有内容都表明您要么必须修改项目typings.d.ts文件,要么使用 HTTP 请求从/assets文件夹或类似文件中检索它,这两种方法都不适合我。
我想要完成的是这个。给定以下目录结构:
/app
/services
/my-service
/my.service.ts
/myJson.json
Run Code Online (Sandbox Code Playgroud)
我需要my.service.ts正在使用的服务@Injectable来加载 JSON 文件myJson.json。对于我的特殊情况,文件旁边会有多个 JSON 文件,这些my.service.ts文件都需要加载。
澄清一下,以下方法对我不起作用:
网址: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);
Run Code Online (Sandbox Code Playgroud)
网址:https : //hackernoon.com/import-json-into-typescript-8d465beded79
摘抄:
解决方案:使用通配符模块名称 在 TypeScript 2+ 版本中,我们可以在模块名称中使用通配符。在您的 TS 定义文件中,例如typings.d.ts,您可以添加以下行:
declare module "*.json" {
const value: any;
export default value;
}
Run Code Online (Sandbox Code Playgroud)
然后,您的代码将像魅力一样工作!
// TypeScript
// app.ts
import * as data from './example.json';
const word = (<any>data).name;
console.log(word); // output 'testing'
Run Code Online (Sandbox Code Playgroud)
有没有其他人有任何想法将这些文件加载到我的服务中而不需要这些方法中的任何一种?
我找到的解决方案是使用 RequireJS,我可以通过 Angular CLI 框架使用它。
我必须将 require 声明为全局变量:
declare var require: any;
Run Code Online (Sandbox Code Playgroud)
然后我可以用来require.context获取我创建的文件夹中的所有文件,以保存../types.
请在下面找到完整的服务,该服务将所有 JSON 文件(每个文件都是一种类型)加载到服务变量中types。
结果是一个类型对象,其中类型的键是文件名,相关值是文件中的 JSON。
type1.json、type2.json和的示例结果:type3.json../types{
type1: {
class: "myClass1",
property1: "myProperty1"
},
type2: {
class: "myClass2",
property1: "myProperty2"
},
type3: {
class: "myClass3",
property1: "myProperty3"
}
}
Run Code Online (Sandbox Code Playgroud)
import { Injectable } from '@angular/core';
declare var require: any;
@Injectable()
export class TypeService {
constructor(){
this.init()
};
types: any;
init: Function = () => {
// Get all of the types of branding available in the types folder
this.types = (context => {
// Get the keys from the context returned by require
let keys = context.keys();
// Get the values from the context using the keys
let values = keys.map(context);
// Reduce the keys array to create the types object
return keys.reduce(
(types, key, i) => {
// Update the key name by removing "./" from the begining and ".json" from the end.
key = key.replace(/^\.\/([^\.]+)\.json/, (a, b)=> { return b; });
// Set the object to the types array using the new key and the value at the current index
types[key] = values[i].data;
// Return the new types array
return types;
}, {}
);
})(require.context('../types', true, /.json/));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4109 次 |
| 最近记录: |