Reading local json via pipe?


I have a pipe that needs to read data stored in a local, static .json to deliver an output. How would I do this?


I never tried it but I think you should use Angular 2 HTTP class.

      // Call map on the response observable to get the parsed people object
      .map(res => res.json())
      // Subscribe to the observable to get the parsed people object and attach it to the
      // component
      .subscribe(people => this.people = people);


There’s one big problem with the approach with using Http - overengineering: involving network in what should be simple file access. Also, http is asynchronous by design, so we jump into promises world without real necessity (local resources are expected to be loaded quickly, so it should be synchronous). With it the UI has to subscribe to wait until the promise will complete, to refresh with the new data.

It would be really interesting to find if there’s some less complicated solution.


I don’t know if you can call it “less complicated”, but if you bundle with webpack, it is trivial to require('people.json'). There may be a way to do something similar with browserify; I don’t know.


Thanks, that’s what I’ve been thinking about too. Used a bit different solution with gulp-merge-json to package resources into TypeScript module:


Cool, but is there a way to use that with js instead of ts?


Yes, it’s pretty simple - just change file name extension (‘i18n.js’ in my example) and change exportModule value to, say, ‘var resources’, to get that object in JavaScript variable. If I understand correctly how ionic assembles Javascript, this variable will be available globally in your app. You’ll also need to rewrite code of pipe to get value by key correctly.