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

Dynamic inheritance in Node.js based on the version being used

Why does the code provided only function correctly in Node.js versions 5.x and 6.x, but not in versions 4.x and older? Is there a way to modify the code so that it can work across Node.js versions 0.10.x - 6.x? 'use strict'; var util = require ...

Issue with angular ui-router transition override/intercepted/disrupted/terminated

Encountering these errors: Error: transition superseded at $StateProvider.$get (http://localhost:1337/angular-ui-router/release/angular-ui-router.js:2903:42) Error: transition prevented Error: transition aborted Error: transition failed After researc ...

Is it possible to utilize the `.apply()` function on the emit method within EventEmitter?

Attempting to accomplish the following task... EventEmitter = require('events').EventEmitter events = new EventEmitter() events.emit.apply(null, ['eventname', 'arg1', 'arg2', 'arg3']) However, it is ...

How to return a variable to Express when clicking a button?

Imagine having a list of 10 elements, each with a unique id as their name, and the user has the ability to add more items to the list at any time. If I were to click on an element, my goal is to have Express retrieve the id of that specific element. If it ...

Removing connected entries with pre middleware on mongoose

I currently have 3 different schemas: Building const BuildingSchema = mongoose.Schema({ address: { type: String, required: true }, numberOfFloors: { type: Number, default: 0 }, }); Apartment const RoomSchema = mongoose.Schema({ roomNumber: { type: ...

Visual Studio Code encounters a Node.js error stating "Module not found"

I have been struggling to run my Node.js program in VSCode. Despite trying various solutions found on StackOverflow, none of them seem to be working for me. I even attempted the Json file method, but unfortunately, that didn't work either. internal/mo ...

Why am I receiving an error message stating "undefined is not a function" when trying

I am attempting to create a popover using the Angular UI pop over feature. I have loaded my HTML and compiled it, but when I run my program and click on the star icon (where I display the popover), I receive an error stating that 'undefined is not a f ...

Ways to turn off hover highlighting

Is there a way to disable the highlighting effect of the <select> element in HTML? When you hover over items in the dropdown list, a blue color strip moves with your mouse. I need to find a way to get rid of this effect. Here is an example of the c ...

Easily validating forms using javascript

I'm attempting to design a basic HTML form and would like to implement javascript for validating the input values. Below is the form tag: <form action="" onSubmit="return formValidation();" method="Post" name="form"> Here is a section of the ...

Only the first column of a row in Flexbox will have a line break when exceeding the

Currently, I am utilizing flex with a row direction for a set of items with fixed widths causing overflow and a horizontal scrollbar, which is the desired outcome. Nevertheless, my requirement is for the first column in these rows to be full-width, while ...

Unable to establish connection with remote database server on Hostinger platform

I've been encountering this persistent error that I can't seem to resolve. I developed my project locally, utilizing a local database. Upon completion, I attempted to manually migrate my database to my hosting provider since it's relatively ...

Use regular expressions to exclude occurrences of the character 'n' from your text

Looking for a regular expression to validate input, specifically filtering out all special characters except "underscore". All characters within the range [a-zA-Z0-9\underscore] are permitted and can appear multiple times. However, my expression shoul ...

Find the elements of <a> tags specifically without the attribute href

Currently, I am extracting the class of all <a> elements in an HTML document of a webpage using VB.net from a WinForm: Dim htmlLinks As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("a") For Each link As HtmlElement In htmlLi ...

Can we access local storage within the middleware of an SSR Nuxt application?

My Nuxt app includes this middleware function: middleware(context) { const token = context.route.query.token; if (!token) { const result = await context.$api.campaignNewShare.createNewShare(); context.redirect({'name': &a ...

Change the state within the click event handler

One issue I'm facing is dealing with 2 submit buttons in my react form. To differentiate between the two buttons, I need to extract the `id` of the one that was clicked using the `onClick` function. Currently, when trying to set the state with this ` ...

To manipulate the array in a more complex manner, either add or remove the item based on its existence: if it's already in the array, remove it; if it

As I prepare to send key-value pairs to the backend in the form of a JSON structure, each representing a category (e.g., customer churn rate), I encounter an issue. The idea is to add checkmarked options to the array of their respective categories. However ...

What is the best way to combine elements from different arrays to create a comprehensive listing?

My current function successfully pulls data from another source to create a listing. However, the data I require is spread across multiple arrays, causing some items to be returned as "undefined." At the moment, I am only fetching data from the products a ...

Creating a personalized tab label in Angular Material's md-tabs

After reading the md-tab Documentation, it seems that custom md-tab-label can be created. I attempted to achieve this as follows: <md-tab-label class="my-label"> Label </md-tab-label> Here is my CSS: .my-label{ background: #40FF00; } ...

Calculate averages of an array and show them when the page loads using Vue

In my coding project, there is an array named products that follows this specific structure: { "_id": "150", "name": "Milk", "description": "Skimmed", "price": "10", "ratings": [ ...

How to style the background color of the selected option in a <select> element using

Is there a specific style I can use to change the color of a selected option in a dropdown menu? For example: <HTML> <BODY> <FORM NAME="form1"> <SELECT NAME="mySelect" SIZE="7" style="background-color:red;"> <OPTION>Test 1 &l ...