Search code examples
jsonangulartypescriptwebpackwebpack-2

How do I serve JSON in Angular?


I have an Angular 4 application built with Webpack, and I am trying to serve a JSON file. Two questions:

  1. In simplest case, JSON file is static. I can't figure out how to set up webpack to include myfile.json the way I include images. That said, if I look at URL of any image on the page, it comes as assets/angular.9db278d630f5fabd8e7ba16c2e329a3a.png. I would prefer to have a simpler URL for my JSON.
  2. In less simpler case, I build the file programmatically. Building a JSON string is, obviously, not a problem, but displaying it is. I looked at examples how to display a PDF, but all of them require plug-in, and most just call window.open in a different window. Since Angular components are displayed within a tag on a web page, I am having trouble "breaking out" of the page.

Is it even possible? I realize, I asked two questions, but I'll be happy with an answer to either one; not to both :)


Solution

  • If you are using webpack 1, you can use json-loader; JSON is loaded by default in webpack 2 (see README for json-loader).

    The JSON can then be imported similarly to images import myFile from ./myfile.json.

    With regards to your other question, without some example code its hard to understand what you are trying to do. It seems that you want to display the created JSON raw on the page outside of the angular application?