Utilizing a shared service for multiple JSON datasets in AngularJS: A beginner's guide

After successfully creating a service that retrieves data from a local JSON file and uses it in a controller to display it in the browser, everything seems to be working well. Here is the code snippet:

JavaScript Code:

var myApp = angular.module("myApp", ['ngRoute']);

myApp.service("dataService", function($http, $q){
   var deferred = $q.defer();
   $http.get('json/link.json').then(function(data){
        deferred.resolve(data);
    });

   this.getData = function(){
     return deferred.promise;
   }
})
.controller("linkCtrl", function($scope, dataService) {
    var promise = dataService.getData();
    promise.then(function(data) {
        $scope.links = data.data;
    });
});

Now I have another JSON link (e.g. json/link2.json) and would like to achieve the same functionality without creating a new service. Is there a way to modify the "dataService" service to work with different JSON data sources?

I'm looking for an approach to repurpose the Service rather than duplicating its functionality. Any suggestions on how I can reuse the Service for handling various types of JSON data?

Thank you in advance!

Answer №1

Simply create a function that takes a URL as an argument:

myApp.factory("fetchDataService", function($http){
   var fetchData = function(url){
      return $http.get(url); // this will give you a promise
   };
   return {
      fetchData: fetchData
   };
})

Now you can utilize it in the following manner:

.controller("apiCtrl", function($scope, fetchDataService) {
    var dataPromise1 = fetchDataService.fetchData('json/data.json');
    dataPromise1.then(function(data) {
        $scope.dataSet1 = data.data;
    });

    var dataPromise2 = fetchDataService.fetchData('json/data2.json');
    dataPromise2.then(function(data) {
        $scope.dataSet2 = data.data;
    });
});

Answer №2

Here is an example you can try out:

myApp.service("dataService", function($http){
 this.fetchData = function(url, callback){
 $http.get(url).then(function(response){
    if(callback)
      callback(response);
   });
});
myApp.controller("linkCtrl", function($scope, dataService) {
    dataService.fetchData('json/link.json', function(data){
      $scope.links = data.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

Why AngularJS's ng-repeat track by obj.id fails to reinitialize transcluded content upon obj.id change

function ManageComponent() { var newVar = this; this.$onInit = function() { newVar.linkURL = 'http://example.com/obj/' + newVar.obj.id; } } function MasterController($scope, $timeout) { $scope.arrObjs = [{id: 1, name: "item1"},{id: 2, ...

There was an error during product validation that occurred in the userId field. In the Node.js application, it is required to

I am in the process of developing a small shop application using node.js, express, and mongoose. However, I have encountered an issue when attempting to send data to the MongoDB database via mongoose. Here is the product class I have created: const mongoo ...

Data structure designed specifically for a drawing tool application

Currently, I am in the process of developing a unique sketching application using the HTML5 Canvas element. Despite my progress, there is one particular challenge that has stumped me. The main concept of the application involves allowing users to manipula ...

How can I add seconds to the jquery datetimepicker plugin?

Looking to implement the datetimepicker plugin from here, but I'm having trouble finding information on how to include the seconds part. Is there a way to add seconds to this plugin? It's a crucial requirement, so any suggestions for another good ...

parsing an array using jQuery's getJSON

Finally got the simplified array to work, check it out below If you're still struggling with parsing a complicated array, you can refer to this link. TLDR: I need to extract and insert each heading from an array into a div using Jquery - getJSON, wi ...

Serialization of nested JObjects results in empty arrays being produced

I've encountered a puzzling scenario where I'm attempting to convert an object received from a third-party API into JSON. Unfortunately, I have no influence over the structure of the API's response or the object it provides. The C# POCO that ...

Ajax successful event fails to trigger

Having Trouble Implementing Okta Authentication with WebForms The login functionality is working, but the redirect part is not functioning correctly I have attempted to use void and return a JSON object/string, but it does not seem to work If I remove th ...

Tips for ensuring that an Ajax request successfully executes when a page loads

I have a question about implementing an AJAX request in my code. Currently, I have the text on the screen updating when a dropdown input is selected using 'onchange'. However, I also want this same behavior to occur on page load, but I am struggl ...

ReactJS instance.render function error: How to solve it?

I encountered a strange error message while working with reactjs, which states that instance.render is not a function in reactjs. Despite my efforts, I have been unable to identify the source of this error. Below are the contents of index.js and search_bar ...

Is there a way to stop vue-panZoom from functioning temporarily?

I am working with a Grid that includes the use of vue-panZoom. Within the Grid, there is a section that utilizes vue-draggable-resizable, similar to what is depicted in the image below: Image When I drag the gray square (vue-draggable-resizable), the bl ...

Mastering the management of various events within React Material UI components

I am working with a Material UI Switch Component and need to detect click events on it. In certain situations, I want to prevent the change event from triggering. What is the most effective way to achieve this? While I have previously used event.preventD ...

Screening new elements to be included in the array

When adding new items to an array in my App, I encountered a problem with filtering the newly added items. If I use .filter by state, it modifies the original array and I am unable to filter from the beginning (original array). I attempted to filter using ...

Encountering an issue when running the command "ng new my-app" after updating the @angular/cli package

npm version 7.5.4 has been detected, but the Angular CLI currently requires npm version 6 to function properly due to ongoing issues. To proceed, please install a compatible version by running this command: npm install --global npm@6. For more information ...

Local host's attempt to retrieve data from an external site via an Axios GET request was rejected

I'm currently attempting to execute a GET request on an external website in order to scrape some information. Unfortunately, my axios GET request is returning a connection error. I suspect that this issue may be related to the fact that I am sending t ...

Unexpected behavior observed when trying to smoothly scroll to internal links within a div, indicating a potential problem related to CSS dimensions and

Within a series of nested div containers, I have one with the CSS property overflow:hidden. My goal is to smoothly scroll to internal links within this specific div using jQuery. The snippet of code below has worked successfully in previous projects: ...

The event listener for the custom cursor in Nuxt.js is failing to work properly when the route

I am currently in the process of constructing a new website for our studio, but am encountering difficulties with getting the custom cursor to function correctly. I implemented a custom cursor using gsap, and it worked perfectly; however, once I navigate t ...

Set checkbox variable to undefined at all times

I am having trouble determining the state (True/False/null, etc.) of my "CSS-only" toggle switch. No matter what I try, I keep getting a null value. I'm not sure why this is happening, but it seems that the checkbox input is not functioning as expecte ...

Please provide several input fields with identical 'name' attributes for submission

I'm encountering an issue with a form where multiple input fields (text) share the same name attribute. On the backend, I am utilizing node.js and Mongoose for a POST method. Below is a snippet of the code: if(existingFruit) { Fruit.findOneA ...

The JSON Schema is flagging validation issues when using a multipleOf value of 0.01 for numbers that end in .49 or .99

Utilizing JSON Schema for validating a server request, I have specific values that need to be validated to two decimal places. The schema I'm using to validate these fields is as follows: 'properties': { 'amount': {'type&a ...

Exploring how PostgreSQL updates a column's data type from JSON to a JSON array

When dealing with a column type of json in PostgreSQL, the data is structured as a json array. An example of this format looks like: [{"attsId": "42a2ce04-52ab-4a3c-8dfb-98c3d14b307d", "planId": 46, "filePath": "fileOperate\\upload", "cfileName" ...