Cameron
Cameron

Reputation: 2965

How to access a JSON file in my controller

In my Ember app, I have a JSON file filled with data in my public directory (I.E. public/data/articles.json.

I have an article route where I would like to load in this data and display it in the front-end. How could I do this successfully? I am willing to use the model hook, however I don't know of a solution off-hand.

I currently have the following code in my controller. However, this doesn't work (most likely because the data is loaded in after it is rendered).

import Controller from '@ember/controller';
import $ from 'jquery';

export default Controller.extend({
  init() {
    this._super(...arguments);
    $.getJSON("/data/articles.json", function (data) {
      console.log("test");
      console.log(data);
      this.articleData = data;
  }
})

Upvotes: 0

Views: 1200

Answers (2)

Lux
Lux

Reputation: 18240

You can literally just write return $.getJSON("/data/articles.json"); in your routes model hook and then access the data as model in your template/controller.

A bit more elegant would be to use fetch:

async model() {
  const res = await fetch('/data/articles.json');
  return res.json();
}

Upvotes: 2

esbanarango
esbanarango

Reputation: 1637

Are you accessing that file somewhere else? I would recommend putting the file inside your app folder and importing it. It could be inside app/utils/sample-articles.js or another folder for "static data". That way you don't have to do that extra request.

// app/utils/sample-articles.js
export default {
  // Articles
};

Then in your controller you can just import it like:

import Controller from '@ember/controller';
import sampleArticles from 'your-app/utils/sample-articles';

export default Controller.extend({
  articleData: sampleArticles
});

Also in your example, you're assigning the value of data to a variable in an inner scope. You would need to refactor that like:

import Controller from '@ember/controller';
import { set } from '@ember/object';
import $ from 'jquery';

export default Controller.extend({
  init() {
    this._super(...arguments);
    $.getJSON("/data/articles.json", (data) => {
      console.log("test");
      console.log(data);
      set(this, "articleData", data); // Use `set`
  }
});

Upvotes: 1

Related Questions