Andrei Andrei - 1 month ago 6
Javascript Question

Angular - Get array from JSON file

Sorry for the noob question but I am just getting started with Angular. I have this array declared in services.js:

var articles = [{
id: 1,
title: 'Article 1 Title',
intro: 'Article 1 Intro',
image: 'photo.jpg',
published: '27/10/2016',
text: 'Article 1 Text',
url: 'http://www.domain.com'
}, {
id: 2,
title: 'Article 2 Title',
intro: 'Article 2 Intro',
image: 'photo.jpg',
published: '27/10/2016',
text: 'Article 2 Text',
url: 'http://www.domain.com'
}];


Now that everything works fine in my Angular App I want to read this array from a JSON file that can be found, for example, at
www.domain.com/articles.json
and it looks like this:

{
"articles": [
{
"id": 1,
"title": "Article 1",
"intro": "Article 1 Intro",
"image": "image.png",
"published": "27/10/2016",
"text": "Article 1 Text",
"url": "http://www.domain.com/article-1"
},
{
"id": 2,
"title": "Article 2",
"intro": "Article 2 Intro",
"image": "image.png",
"published": "27/10/2016",
"text": "Article 2 Text",
"url": "http://www.domain.com/article-2"
}
]
}


How can I make this change?

Answer

To get the data of the file in your Angular app, you'll have to get the file's contents through an HTTP request. The easiest way to do this is by using the $http service.

Example (with relative url):

$http.get('/articles.json').then(function (response) {
    var articles = response.data.articles;

    // Do something with articles...
});

The callback function you're passing to the then method will be called when the HTTP request was successful. Note that your data will only be available in this callback function. Also don't forget to include a dependency to the $http service in your controller. ;)