Loading JSON Without an HTTP Request

Viewed 4528

I am working on a project using Angular 4, NPM, Node.js, and the Angular CLI.

I have a rather unusual need to load JSON into an Angular service (using an @Injectable) without an HTTP request, i.e. it will always be loaded locally as part of the package, and not retrieved from a server.

Everything I've found so far indicates that you either have to modify the project's typings.d.ts file or use an HTTP request to retrieve it from the /assets folder or similar, neither of which is an option for me.

What I am trying to accomplish is this. Given the following directory structure:

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

I need the my.service.ts service, which is using @Injectable, to load the JSON file myJson.json. For my particular case, there will be multiple JSON files sitting next to the my.service.ts file that will all need to be loaded.

To clarify, the following approaches will not work for me:

Using an HTTP Service to Load JSON File From Assets

URL: https://stackoverflow.com/a/43759870/1096637

Excerpt:

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

Modifying typings.d.ts To Allow Loading JSON Files

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

Excerpt:

Solution: Using Wildcard Module Name In TypeScript version 2 +, we can use wildcard character in module name. In your TS definition file, e.g. typings.d.ts, you can add this line:

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

Then, your code will work like charm!

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

The Question

Does anyone else have any ideas for getting these files loaded into my service without the need for either of these approaches?

3 Answers
Related