Creating a factory in AngularJS to handle RESTful JSON communication with

I have a scenario where I need to call a factory from multiple controllers in order to fetch JSON data. When I tried calling the factory directly from the controller, it worked successfully. However, after adding a factory and checking the console for errors (which is empty), nothing appears on the screen either. Here is the code snippet that illustrates the issue:

HTML template:

<!-- Schools -->
<div class="row">
    <h3 class="text-center">Schools and Associations</h3>
    <ul class="gallery gallery1" ng-controller="SchoolsCtrl">
        <li ng-repeat="school in schools" class="card">
            <a ng-href="{{school.url}}" target="_blank">
                <img ng-src="{{school.thumbUrl}}" class="img-responsive">
                <p class="text-center">{{school.name}}</p>
                <p class="text-center">{{school.time}}</p>
            </a>
        </li>
    </ul>
</div>

controller.js:

var mainApp = angular.module('mainApp', ['bootstrapLightbox', 'ngAnimate']);

mainApp.controller('CompaniesCtrl', function($scope, GalleryService) {
$scope.companies = GalleryService.getObjects('app/common/companies.json');
});

mainApp.controller('WorksCtrl', function($scope, GalleryService) {
$scope.works = GalleryService.getObjects('app/common/freelance-projects.json');
});

mainApp.controller('SchoolsCtrl', function ($scope, GalleryService) {
$scope.schools = GalleryService.getObjects("app/common/schools.json");
});

service.js:

mainApp.factory('GalleryService', function ($http) {
    return {
        getObjects: function (jsonUrl) {
            $http.get(jsonUrl)
                .success(function (data) {
                    return data; 
                })
                .error(function (data, status, error, config) {
                    return [{heading:"Error", description: "Could not load json data"}];
                });
        }
    }
});

Answer №1

To access data from the factory function getObjects, you need to ensure that getObjects returns a promise with a .then function for chaining promises. Within your controller, you can call getObjects and utilize .then function callbacks to handle the response.

Factory:

mainApp.factory('GalleryService', function ($http) {
    return {
        getObjects: function (jsonUrl) {
            return $http.get(jsonUrl)
                .then(function (resp) {
                    return resp.data; 
                }, function (res) {
                    return [{heading:"Error", description: "Could not load json data"}];
                });
        }
    }
});

Controller:

var mainApp = angular.module('mainApp', ['bootstrapLightbox', 'ngAnimate']);

mainApp.controller('CompaniesCtrl', function($scope, GalleryService) {
  GalleryService.getObjects('app/common/companies.json').then(function(data){
    $scope.companies = 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

Struts2 iterator failing to print any output while traversing through JSON string

My Struts 2 application is set up to display data by iterating through a JSON object stored in the Struts2 session using the Struts2 iterator as shown below: <s:iterator var="menu" value="userMenu.get('permissions')"> <s:property val ...

Issue encountered while constructing my application (utilizing the "yarn run build" command and in Vercel)

Encountered an error during the build process, whether on the server or locally. This issue arises when using package managers like yarn, npm, and others. The error specifically points to a problem in the CSS file, but it only occurs in the production bu ...

Convert JSON to CSV using jq and handle sublists by splitting them into multiple records

As I work on parsing a JSON response from the Azure RateAPI, my goal is to convert it into a standard CSV file. The current method I'm using to achieve this conversion works well, but there's an issue with one of the attributes being a list. For ...

What could be causing my SVG bezier curves to malfunction in Firefox?

Encountered an issue today where diagrams I have generated are not functioning properly in Firefox when created using the getPointAtLength method. Here is a demonstration of the problem: http://jsfiddle.net/xfpDA/9/ Please take note of the comments at th ...

Is it possible to relocate content using JavaScript for SEO purposes?

For SEO purposes, I initially inserted a text early in the html code, but from a visual standpoint, this text should actually appear at the bottom of the page. Unfortunately, using just CSS won't allow me to achieve this. My question is: would moving ...

Unable to transfer the json data to the function

How can I get the JSON data from a localhost database and put it into an ArrayList? I've tried calling the parseJSON function but keep getting a null JSON. Where should I call the function to ensure success? @Override protected String doInBackground ...

What is the method for selecting a check box in AngularJS?

I am struggling with two lists (List 1 and List 2) of checkboxes that have three items in common. The issue I'm facing is that when I check an item in List 1, the corresponding item in List 2 also gets checked, which should not happen. I need to find ...

Activate filtering beyond the AngularJS datatable

Currently, I am experimenting with a codepen to understand how to filter data based on a clicked span element. The table is where the data is displayed and I'm looking for a way to trigger filtering outside of it. While the angularjs documentation spe ...

Can we send a dynamic form using AJAX?

I am seeking a method to submit a page filled with quantities to another page and then retrieve their values. Here is my setup: <input type="number" name="item1" /> <input type="number" name="item2" /> <input type="number" name="item3" /> ...

Building a JSON tree model in a Spring application using a list

I'm struggling with JSON. I have a user_id from the client-side and need to check the groups associated with this user_id. After retrieving data from the database, I place it into a list. I have included this annotation in my xml file: <mvc:anno ...

Implement a cron job in Node.js to automatically trigger an Express route on a weekly basis

I need to run tests on a certain page every week by creating a cron job that will access my express route at regular intervals. Currently, I have set up a cron job to run every 2 minutes as a test: //schedule job every 2 minutes schedule.scheduleJob("* /2 ...

Maneuvering through JavaScript pop-up boxes in Selenium using Python

Currently, I am working on automating a webpage using Selenium webdriver in Python. However, the process encounters a Captcha verification at one point. To surpass this obstacle, I decided to manually input the Captcha through a JavaScript dialog box pop-u ...

What is the best way to retrieve the value of a cell in the parent gridview while navigating through the child gridview?

I am facing an issue with a JavaScript function that is used to expand and collapse a child gridview inside its parent gridview. My problem arises when I try to retrieve the value of a specific cell in the current row of the parent gridview, or even just i ...

What is the best way to retrieve a ReactElement from the DOM?

Imagine I have a ReactElement displayed on the screen: <div id="container" data-reactid='reactid.2'></div> To access the HTMLElement, you can use the following code: var element = document.getElementById('container'); ele ...

Develop a personalized event using JavaScript and activate it

I have encountered a problem with a Google ad that expands on click and closes when the close button is hit. However, due to changing conditions, I now need it to expand first and then automatically close after a certain time. Additionally, every time it e ...

Displaying array data without the need for a loop in Vue.js and Axios

I want to display data in my Vue.js 3 app without using a loop. Here is the response from my Axios API: In My Axios Api I got reponse: [{id: 2, name: "sub_title", value: "The Best Developer Team", created_at: null, updated_at: null},… ...

Is it necessary to configure Webpack or use a plugin to remove console.log() statements by default in an Angular Application, or does it do so automatically?

Welcome to my first post! I hope I can effectively communicate the question and the background that led me to ask it. I am relatively new to web programming, with about 1 and a half years of experience working with Java, JavaScript, and TypeScript using An ...

Displaying data based on specific identifiers in AngularJS

How can I update information based on the unique ID provided in a JSON file. JSON: { "hotels": [ { "id" : 1, "name": "some hotel 1", "category" : [{ "id" : 1, "hotel_id" : 1, "name" : "Cat name 1", "bn ...

Node.js Implementation of HTML Content

Currently, I am attempting to iterate through a list of items and generate HTML code to be passed into the view file: const itemWrap = '<div id="items"></div>'; userDetails.notes.forEach(item => { const itemE ...

Conceal the div until the animation with a delay of `1s` has finished, then reveal it afterwards

I have incorporated a CSS file to introduce animations on the website I am currently developing. You can find it here: The premise of this CSS file is straightforward - by adding specific class names to div elements, you can animate them as you scroll up ...