Pull data from two JSON files using Angular's $http.get function

Extracting information from 2 different JSON files:

1st JSON file 'names.json':

  
[
    {
        "name": "AAAAAA",
        "down": "False"
    },
    {
        "name": "BBBBBB",
        "down": "45%"
    },
    {
        "name": "CCCCC",
        "down": "12%"
    }
]

Second JSON file 'data.json'

[
    {
        "data": "25-12-2014"
    }
]

Javascript:


app.service('service', function($http){
    this.getNames = function () {
        var data = $http.get('data,json', { cache: false });
        var names = $http.get('names.json', { cache: false });
        return names;
        return data;
    };
});

app.controller('FirstCtrl', function($scope, service) {
    var promise = service.getNames();
    promise.then(function (data) {
        $scope.datas = data.data;       
        console.log($scope.datas);
    });
})

HTML


<div ng-controller="FirstCtrl">
    <table>
        <tbody>
            <tr ng-repeat="name in datas">
                <td>{{name.name}}</td>
                <td>{{name.data}}</td>
            </tr>
        </tbody>
    </table>
</div>

Despite accessing both JSON files in the JavaScript code, I am only able to display data from 'names.json' in my console.log and table. How can I also display data from 'data.json'? Thank you.

Answer №1

To effectively handle returning multiple promises in a single function, utilize $q.all to consolidate them.

Function Example

// Inject $q into the service function
this.getNames = function () {
    var data =  $http.get('data.json', { cache: false});
    var names =  $http.get('names.json', { cache: false});
    return $q.all([data, names]);
};

Controller Implementation

var promise = service.getNames();
promise.then(function (data) {
    $scope.datas = data[0].data;
    $scope.names = data[1].data;
});

Answer №2

Update your code with the following changes

app.service('apiService', function($http) {
    return{
        fetchData : function(){
            return $http.get('data,json', { cache: false });
        },
        fetchNames : function(){
            return $http.get('names.json', { cache: false });
        }
    }

});

app.controller('MainController', function($scope, apiService, $q) {
    $q.all([apiService.fetchData(), apiService.fetchNames()]).then(function(response){
        $scope.data = response[0].data;
        $scope.names = response[1].data;
    });
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Disregard recurring keys within JSONObject

Currently, I am dealing with a String that is in JSON Format String str = "{\"innerkey1\":\"innervalue1\", \"innerkey2\":\"innervalue2\",\"innerkey1\":\"innervalue3\"}"; While attempting to inst ...

Encountering a browser error when trying to access a C# method via AJAX: Javascript

I'm having trouble connecting to my Webservice. I keep getting an error 404, even though everything seems like it should be working fine. The issue started when I moved the code from my *.cshtml file into a separate .js file. The Javascript file is l ...

JavaScript OOP problem with object instances

I'm currently working on developing an app in JavaScript and trying to grasp the concept of Object-Oriented Programming. I created a simple "class" where I set an empty array in its prototype. However, when I create objects from this class and pass va ...

Is there a way to incorporate JavaScript or jQuery into my navigation bar?

I'm working on implementing JavaScript into my navbar. My goal is to create functionality where clicking on a button changes its class to 'active' while the other buttons revert back to their normal state. <ul> <li><a class=&q ...

A process of associating a single object with an array containing numerous objects

Can someone help me convert the following data structure? { role:'admin', resource:['calendar','appraisal'], action:['create:any','read:any','update:any','delete:any'] } { role:&apos ...

`Inability to remove item from array in Vue.js`

I've been struggling to understand why this feature isn't functioning as expected. I'm using sample code for reference, but it's not behaving the same way. When I click on the delete button, nothing happens even though it should remove ...

Check the existence of a file before including it in AngularJS using ng-include

In my AngularJS app, I am utilizing ng-include to bring in a partial file. If the specified partial .html file does not exist, I need to implement an alternative solution. The name of the partial is derived from $location.path(). For example, if the path ...

Create an object name in an Angular factory or service by utilizing the initial and final dates contained within an array

I have a method in my Angular service/factory that accepts an array of arrays containing objects [[{},{}],[{},{}]] as a parameter. The parameter structure consists of arrays representing weeks, with each day's object containing a date and an integer ...

Here's a step-by-step guide on how to parse JSON information in JavaScript when it's formatted as key-value

I need to parse the JSON data in JavaScript. The data consists of key-value pairs. Data looks like this: {09/02/2014 15:36:25=[33.82, 33.42, 40.83], 08/11/2014 16:25:15=[36.6, 33.42, 40.45], 07/30/2014 08:43:57=[0.0, 0.0, 0.0], 08/12/2014 22:00:52=[77.99 ...

Error: NextJS Client-Side Rendering Issue

I find this situation quite perplexing... Everything seems to be working fine except for the onClick code and useEffect code. I attempted running document.querySelector('button'); in the console, but it returned undefined. It appears that JavaSc ...

What methods can be used to deeply filter in Angular using the 'filter' function?

Let's imagine I have various items stored in an array: app.controller('ItemsController', function() { this.items = [ {}, { name: 'apple', }, { ...

Find the position of an element in an array that includes a specific string value using JavaScript or Node.js

I need help figuring out how to find the index of an array that contains or includes a specific string value. Take a look at my code below to see what I've tried so far: Here is a simple example: var myarr = ["I", "like", "turtles"]; var arraycontai ...

Create dynamic combo boxes using jQuery

My goal is to display a text field on the page if a user has only one credit card number in the database. However, if the user has multiple credit card numbers stored, I want to display all of them in a combo box. Below is the ajax response that I am rece ...

Convert an xlsx file into a structured json format for better organization and access

I'm looking to structure a JSON file like the image below: https://i.sstatic.net/YtZ7q.png Instead of using numbers, I want to use the Food value, and under each Food value, I want to include the amount of calories. Any suggestions on how to achiev ...

Utilize the request object from Express within a Mongoose Plugin

I have incorporated an API in ExpressJS along with a middleware that runs before each endpoint controller: app.use(segregationMiddleware); app.get('/some-endpoint', controller1); app.get('/some-endpoint-2', controller2); The segregat ...

How does Backbone.js tackle error handling when receiving messages from Rails?

Can anyone using backbone.js lend a hand? How can error messages from a rails app be encoded when integrating with backbone.js? For instance, how should flash messages like "record not found" be handled? While errors are usually defined on the client sid ...

Verifying StartDate and EndDate using AngularJS and Bootstrap Datepicker

My HTML Coding <form name="myForm"> <div class="row"> <div class="col-md-2"> <input data-ng-model="Data.StartDate" type="text" id="startDate" name="startDate" class="form-control" data-da ...

"Utilizing Vuex: Fetch data from API when the first getter is accessed, and subsequently retrieve it from the local

I have a Vuex instance that is responsible for fetching data from an API. The initial access to the store should trigger a call to load the data from the API. Subsequent accesses should return the previously loaded data stored in store.empresas. This is th ...

A method for determining the quantity of <li> elements within a <ul> container while applying specific conditions

I am currently using document.querySelectorAll('ul > li').length to count the total number of items in my list. However, I am wondering if there is a way to count only those items that meet a specific condition. For example: <ul> < ...

Creating a TypeScript module declaration for exporting a class

Just starting out with TypeScript and running into issues while trying to load an es6 javascript module. Here's the code snippet from my javascript file: //TemplateFactory.js export class TemplateFactory{ static getTemplate(module){ } } In ...