Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading JSON Without an HTTP Request

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?

like image 631
StephenRios Avatar asked Jun 01 '17 16:06

StephenRios


People also ask

How do I access a JSON object?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.

Are HTTP requests in JSON?

JSON is most commonly used in asynchronous HTTP requests. This is where an application pulls data from another application via an HTTP request on the web.


1 Answers

You will get an error if you call json directly, but a simple workaround is to declare typings for all json files.

typings.d.ts

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

comp.ts

import * as data from './data.json';
like image 132
Dylan Avatar answered Oct 07 '22 01:10

Dylan