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

Loading JSON Without an HTTP Request

我正在使用 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。对于我的特殊情况,将有多个 JSON 文件位于 my.service.ts 文件旁边,所有这些文件都需要加载。

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

使用 HTTP 服务从资产加载 JSON 文件

URL:

摘录:

// 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 文件

URL: 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'

问题

其他人是否有任何想法可以将这些文件加载​​到我的服务中而不需要这些方法中的任何一种?

您可以从构造函数中定义的对象直接访问服务中的变量。

...假设您的构造函数像这样加载服务

constructor(private someService:SomeService){}

您只需 someService.theJsonObject 即可访问它。

请注意不要在加载它的服务函数加载它之前执行此操作。然后你会得到一个空值。


您可以像在组件文件中一样为服务文件分配变量。

只需在服务中声明它们

public JsonObject:any;

并且(最简单的方法)是让调用您的服务的函数为您分配 JSON 对象。

假设您这样调用服务

this.serviceObject.function().subscribe
(
  resp =>
  {
    this.serviceObject.JsonObject = resp;
  }
);

完成一次后,其他组件可以使用 someService.theJsonObject 访问该 JSON 内容,如前所述。


在你的情况下,我认为你需要做的就是将你的 JSON 对象嵌入你的代码中。也许你可以使用 const。这不是糟糕的代码或任何东西。

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

typings.d.ts

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

comp.ts

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

我找到的解决方案是使用 RequireJS,我可以通过 Angular CLI 框架使用它。

我必须将 require 声明为全局变量:

declare var require: any;

然后我可以使用 require.context 获取我创建的文件夹中的所有文件,以保存 ../types 中的类型。

请在下面找到将所有 JSON 文件(每个文件都是一种类型)加载到服务变量 types.

中的完整服务

结果是类型的对象,其中类型的键是文件名,相关值是文件中的 JSON。

从文件夹 ../types:

加载文件 type1.jsontype2.jsontype3.json 的示例结果
{
    type1: {
        class: "myClass1",
        property1: "myProperty1"
    },
    type2: {
        class: "myClass2",
        property1: "myProperty2"
    },
    type3: {
        class: "myClass3",
        property1: "myProperty3"
    }
}

最终服务文件

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