What is the best way to change an http call in a controller to a Service/factory pattern that accepts a parameter?

Currently, I have a controller making use of http.get, http.push and http.post methods within my AngularJS app.

During my learning journey with AngularJS, I've discovered that it's more efficient to place http.get calls in service files. While I can easily handle simple http.get requests, I find myself struggling with http.get by id or when passing parameters for http.get/http.post calls.

Here is a snippet of my current controller:

angular.module("app-complaints")
.controller("clcontrol", clcontrol);

function clcontrol($routeParams, $http, $scope) {
    $http.get(baseURL + "/api/complaints/" + $scope.complaintCase + "/checklists")
        .then(function (cl) {
            //success
            $scope.index = 0;
            $scope.cl = [];
            $scope.cl = cl;

I aim to refactor it like this:

controller.js

angular.module("app-complaints")
.controller('clcontrol', function ($http, $scope, $q, Service, $timeout) {
....
getCL();
function getCL(){
Service.getCl()
.success(function(cl){
$scope.cl = [];
$scope.cl = cl;
}

service.js

angular.module("app-complaints")
.factory('Service', ['$http', function ($http) {
        Service.getCL = function () {
        return $http.get(urlBase + "/api/complaints/" + complaintCase + "/checklists")
    };

 };

Answer №1

Here's a simple solution: Create a factory that accepts parameters.

var app = angular.module("MyApp", [ /* dependencies */]);

app.factory("SharedServices", ["$http", function($http) {
    return {
        getItems: function(url, parameters) {
            return $http.get(url, {
                //include optional query string like {userId: user.id} -> ?userId=value
                params: parameters
            });
        },
        postItem: function(url, item) {
            var payload = {
                item: item
            };
            return $http.post(url, payload);
        },
        deleteItem: function(url, item) {
            var payload = {
                item: item
            };
            return $http({
                url: url,
                data: payload,
                method: 'DELETE',
            });
        }
        // Continue this pattern for other methods like PUT and POST as needed
    };
}]);

Utilize the service in your controller:

app.controller("MainCtrl", ["$scope","SharedServices", function($scope, SharedServices) {

    //use shared service functions here
    $scope.postMyThings = function() {
        SharedServices.postItems('path/to/api', itemsArray).then(function(response) {
            //handle success callback and work with response.data
        }, function(response) {
            //an error occurred
        });
    };

    $scope.getMyThing = function() {
        SharedServices.getItems('path/to/api/get').then(function(response) {
            //handle success callback and work with response.data
        }, function(response) {
            //an error occurred
        });
    }

}]);

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

Controlled Checkbox Component in React

I'm really struggling with this. While I can easily work with select drop downs and text fields, I just can't seem to get checkboxes to function properly in a controlled manner. I want them to 'toggle' and respond to events in a parent ...

Implementing a dual hover effect on a Div element

I am working with HTML code that includes an image and text <div class="subcontainer1"> <img src="a.png" alt="" class="imgcolumn"> <h3 class="header3">Hello</h3> </div> This setup places the content above the image. ...

Guidelines for ASP.NET MVC 4: Delivering a file from a controller to a view using AngularJS

I am having trouble downloading a file from the server, despite following various examples. Here is the code snippet that I have been using: Controller (ASP NET MVC): public HttpResponseMessage GetFile(string filename) { try ...

Failed to build development environment: Unable to assign the attribute 'fileSystem' to a null value

I'm attempting to launch an Ionic 2 Application, but I keep encountering this error when running ionic serve Error - build dev failed: Unable to assign a value to the 'fileSystem' property of object null Here is the complete log: λ ion ...

Tips for displaying dynamic content in VueJS?

I'm currently working on an app that allows users to choose which type of vuetify element they want to display on the page. There are 4 options available for selection. My goal is to render the corresponding vuetify component when a user clicks on the ...

Can images be sent to an Express API using SvelteKit's `on:change` event handler in combination with Form Actions?

I have a SvelteKit application that interacts with an Express API to store user data. Within my app, there is a form containing an input file field where users can upload images to be saved on the Express server using Form Actions. The issue I am facing ...

AJAX function in Chrome console is throwing an error message stating "Unexpected Token }"

Dealing with this issue has been quite unusual for me. I've spent the last 3 days trying to troubleshoot it, but now it's no longer bothering me. The situation involves a button and a textbox that sends the data from the textbox to a PHP page whe ...

ExpressJS encountered an error due to an unsupported MIME type ('text/html') being used as a stylesheet MIME type

Whenever I start my NodeJS server and enter localhost:8080, I encounter the mentioned error while the page is loading. The head section of my index.html file is provided below. It's puzzling to me why this error is happening, considering that my index ...

Inserting HTML code into the polymer

This is my HTML code: <div id="setImgWrap"> <!-- The appended image will be displayed here --> </div> Here I am appending an image from JavaScript: this.addedImages = { imageURL:self.downloadURL }; this.$.setImgWrap.append('& ...

What's the most effective approach to verify if all visible input fields possess a value? (excluding the use of jQuery validator

In order to ensure that all necessary fields are selected, I need to implement a check upon clicking a button. Below is the HTML code: <input type="text" class="required-entry"> <input type="text" class="required-entry"> <input type="text" ...

Will my JavaScript function be triggered when the page is resized while printing?

I have a simple HTML layout where I am using the TextFill jQuery library to automatically adjust the text size based on available space. Everything looks good on screen, but when printed, it seems like the page is resized and the JavaScript needs to be re ...

The issue with setting width using % in React Native is causing trouble

While working on my project using expo react native, I encountered an issue with a horizontal scrollview for images. When I style the images using pixels like this: <Image code... style={{width: 350}}/>, everything works fine. However, if I try to ch ...

Capturing C# log data for JavaScript interactions

Can anyone provide recommendations on how to capture JavaScript interactions in a browser using C#? I am interested in developing a web crawler that can track these interactions, allowing me to search for potentially harmful calls. ...

Looking to $post the text strings within select boxes, rather than just their values

Looking to extract the text of select boxes, rather than just their values. HTML : <select name="one" id="one"> <option value="0">Select *</option> <option value="3000">Plan A</option> <option value="6000"> ...

Menu that sorts items based on a specified range of values entered by the user

I'm looking to implement a customized filtering dropdown menu, similar to the one showcased on this website Currently, I have functioning filters that can select items based on a specific category. However, I want to enhance the functionality by inc ...

encountering an issue while working with Selenium on Google Colab

I'm attempting to perform web scraping with selenium in Google Colab and running into some errors The webpage is prompting me to enable JavaScript and disable any ad blockers. I tried enabling JavaScript by adding the following line of code: chrome_o ...

Ways to reload an independent page in order to access PHP session variables:

Starting off, I want to mention that my approach may not be the most efficient. As a novice in JavaScript and PHP, I am aware that there are better and simpler ways to achieve what I'm attempting. The issue seems to be related to session variables an ...

Exploring the intricacies of React's useEffect: Solving the challenge of updating data when two separate dependency arrays are

I am facing an issue with two different useEffect hooks where the dependency arrays are different. const [dateFilterSort, setDateFilterSort] = useState({ queryText: initialQueryText(params.sortName), cardText: initialCardText(params.sortName), ...

Showing a variety of pictures within a specified time frame

In my CSS, I have defined classes that allow me to display different background images on a page at set intervals: .image-fader { width: 300px; height: 300px; } .image-fader img { position: absolute; top: 0px; left: 0px; animation-name: imagefade; ...

Using Javascript and jQuery to create an infinite animated background change with fade effect

I am struggling to figure out how to automatically change the background of a div every 3 seconds, looping through a series of images. I posted about this issue before but didn't receive much help. function animate() { change1(); change2() ...