Design a personalized http service using pure AngularJS to fetch an external JSON file

One of the challenges I'm facing is with an http service that retrieves external json files and populates a grid.

The issue arises when I attempt to use this http service in different controllers. I need to create a custom http service that can be utilized across various controllers while maintaining the same functionality (fetching external Json file).

$http.get('../JSON/permanentEmployees.json').
success(function(data, status, headers, config) {
    $scope.masterArray = data;
}).
error(function(data, status, headers, config) {
    $scope.errorMessage = "Requested grid data file does not exist";
});

This is my current setup for the http service. Any suggestions on how to improve this would be highly appreciated. Please keep in mind to use only AngularJS.

Answer №1

Encapsulate the code within a factory and utilize it. It is advisable to employ a factory in this scenario; you can find more information here. Please note that creating a mockup of the request to JSON was not feasible, so ensure to verify with your JSON.

JSFiddle: here

app.factory('customHTTPService', function($http){
  return {
    getRequest: function(url) {
      return $http.get(url).
      success(function(data, status, headers, config) {
        return {data: data, errorMessage: "Success"};
      }).
      error(function(data, status, headers, config) {
        return {data: "", errorMessage: "Requested grid data file does not exist"};
      });
    } 
  }
});

To implement in the controller, use the following:

app.controller('MyController', function MyController($scope, customHTTPService) {
    $scope.data = customHTTPService.getRequest('../JSON/permanentEmployees.json').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

What is the best way to have a sound play when the page is loaded?

Is there a way to automatically play a sound when the page loads? <audio src="song.mp3"> Your browser does not support the audio element. </audio> I've attempted it with the following method: <script type="text/javasc ...

Angular2 and Firebase App unable to Compile due to TypeScript Issue

Latest Update: The recent issue causing the app to crash upon launch has been successfully resolved. Interestingly, it was not due to TypeScript compilation errors. In the Git repository's main.ts file, all that was needed was a simple line change: ...

What is the best way to create an arrow with text inside using HTML, CSS, and React?

https://i.sstatic.net/u5SoF.png My attempt at creating a position: relative did not work well with my adaptive site layout. I then tried making an SVG image, but it couldn't contain text. Any suggestions on how to achieve this? ...

Tips for including attributes in form input HTML tags

Is there a way to modify an attribute of an HTML element? I attempted the following code snippet, but the attribute does not seem to be updating as expected. $(document).ready(function() { $('#username_input').attr('value', 'som ...

Deactivating the submit button after a single click without compromising the form's functionality

In the past, I have posed this question without receiving a satisfactory solution. On my quiz website, I have four radio buttons for answer options. Upon clicking the submit button, a PHP script determines if the answer is accurate. My goal is to disable t ...

Searching for an item's position based on two specific keys

Is there a way to find the index of two keys with specific values in an object? let myObj = { "value1":[1,2,3], "value2":[2,3,4]}; I am trying to locate the index when myObj.value1==1 && myObj.value2==2, but I can't figure it out. edit : pe ...

Quickly view products in Opencart will automatically close after adding them to the cart and redirecting the

I've integrated the product quickview feature into my OpenCart theme, which opens a product in a popup. However, when I add a product to the cart from the popup, it doesn't update on the main page until I refresh. I'm looking for a way to re ...

Creating a list in React and adding a delay using setTimeout() method

I'm a beginner when it comes to working with React and I've been attempting to display a list of posts using a JSON array. My goal is to have the list render after a certain number of seconds, but for some reason, the list isn't rendering us ...

What steps can be taken to disable Angular's automatic trimming of fields?

Is there a global way to prevent Angular from automatically trimming input fields throughout the entire application? I know that I can avoid it for specific fields using the ngTrim directive, but it's not ideal to add this directive to every text fiel ...

Having difficulty accessing node_modules directory in JavaScript

I am confused about how to access node_modules for JavaScript. Can someone provide an example of calling module.exports from a node_module folder after installing a package with NPM in Node.js? File tree structure: There is a folder named 'ethereum&a ...

What is the best way to pass route props using the <router-link> component?

Check out the button below that links to a specific route: <router-link class="q-pa-md" :to="{ name: 'Edit'}" id="item.id"> <q-btn outline>Edit</q-btn> </router-link> Take a look at my router se ...

Add a custom Leaflet JS control button with personalized text and hover functionality

I successfully completed a control-button-leaflet tutorial and it worked for me. Now I have some additional requirements: Show some text when hovering over the button (similar to the zoom buttons) Change the button's color when hovering over it Abil ...

"Exploring the Effects of Opacity Gradation in

Is there a way to create a face with an opacity gradient in three.js since rgba is not supported and the alpha is not used? I've heard it might be achievable with a ShaderMaterial and custom attributes, but being new to WebGL, I'm still trying t ...

Retain the chosen choice even when the updated options list no longer includes that value

I am using a select element with ngOptions that is based on an array. The contents of this array may change dynamically. However, when the new array value does not include the selected option value, the selectController sets the option value to undefined. ...

Using the `$http.get` method to access a resource in AngularJS

How can I refactor the code below to use $resource instead of $http.get? //The created resource (not currently used) hq.factory('LogsOfUser', function ($resource) { return $resource('/HQ/Graph/GetLoggedinTimes?userName=:userName', ...

All you need to know about the impressive world of HTML5

When the server sends coordinates for a shape like a rectangle, rhombus, circle, trapezium, or polygon and I am uncertain about which one will be received, how should I decide on the figure to draw on the canvas using the Angular framework? ...

Issue with Bootstrap Tags Input and AJAX causing form input value to remain static regardless of readyState

I am facing an issue with my HTML form setup: <form method="post" action="./results.php"> <input type="submit" name="submitbtn" id="submitButton" class="btn btn-default btn-responsive" role="button"> <input name="q" id="query" value ...

Identifying when the mouse cursor changes on a website

Is there a way to detect when the mouse cursor changes as it hovers over different page elements? An event similar to this would be ideal: window.onmousecursorchange = function(e) { // e would provide information about the cursor // for example, ...

Eliminate any blank elements from the Array

My current array is as follows: [home, info, mail,,,, something, stuff, other] I am looking to remove or replace the ,, with just a , Attempting with the method: allIDs.replace(",,", ","); has not yielded desired results when working with arrays The rea ...

The import 'react-router' does not include an export called 'browserHistory'. This issue is coming from the /src/App.js file

I've recently started diving into the routing section of learning react, but I'm a bit puzzled by the error message I encountered. Error: Failed to compile ./src/App.js 31:19-33 'react-router' does not contain an export named 'bro ...