Utilizing an array to pass a series of items to a function parameter

I am currently working on an Angular project that involves a controller and service.

In this setup, the controller sends data and an endpoint to the service.

As of now, the service handles the http request. However, I am in the process of refactoring my code so that the service can match the endpoint from an array list.

This is how the Controller looks:

app.controller('MyController', function($scope, myService) {

    $scope.buttonClick = function(endpoint) {
        myService.postAction(endPoint, $scope.postData)
            .success(function (data, status, headers, config) {

                console.log("success");                   

            })

            .error(function (data, status, headers, config) {

               console.log("error");                    

            });
    }

And here's the MyService code:

app.factory('MyService', function ($http) {

    var endPoints = [
        'cart/cartDetails',
        'customer/addressInfo',
        'payment/ShippingInfo',
    ]

    return {
        postAction: function(endPoint, postData) {
            return $http({
                method: 'POST',
                url: endPoint,
                data: postData,
                headers: {'Content-Type': 'application/json'}
            });
        }
    };
});

When a button is clicked using $scope.buttonClick, one of the endpoints is passed like so:

<button ng-click="buttonClick('ShippingInfo')>Shipping</button>
<button ng-click="buttonClick('addressInfo')>Address</button>
<button ng-click="buttonClick('certDetails')>Cart</button>

Answer №1

Make sure your endPoints are defined as an object

app.factory('MyService', function ($http) {

    var endPoints = {'certDetails': 'cart/cartDetails','addressInfo': 'customer/addressInfo','ShippingInfo': 'payment/ShippingInfo'}


    return {
        postAction: function(endPoint, postData) {
            return $http({
                method: 'POST',
                url: endPoints[endPoint],
                data: postData,
                headers: {'Content-Type': 'application/json'}
            });
        }
    };
});

Answer №2

It is not advisable to proceed with that approach, as the controller would need to know at least the key of the URL endpoint. It would be more efficient to implement the following modification in your factory code:

var endPoints = {'certDetails': 'cart/cartDetails',
                 'addressInfo': 'customer/addressInfo',
                 'shippingInfo': 'payment/ShippingInfo'}


return {
    postCertDetails: post(endPoints['certDetails']),
    postAddressInfo: post(endPoints['addressInfo']),
    postShippingInfo: post(endPoints['shippingInfo'])
};

function post(endpoint){
    return function(postData){
        return $http({
            method: 'POST',
            url: endpoint,
            data: postData,
            headers: {'Content-Type': 'application/json'}
        });
    }
}

Implementation in the controller:

service.postCertDetails({...your 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

Tips on saving Firebase Storage image url in Firebase database?

How do I store the URL of an image uploaded to Firebase Storage in Firebase Database? When executing the code below, I encounter the following error: Uncaught (in promise) FirebaseError: Function DocumentReference.set() called with invalid data. Unsuppor ...

What is the time complexity for finding a specific value in a two-dimensional matrix?

The challenge at hand is quite straightforward: develop an algorithm that can determine if the target value exists within the given matrix. Here, I have devised two potential solutions. However, I am uncertain as to which one would be more efficient. Perso ...

Using Javascript, populate an array with Enum variable values

Hey there! I've got this code that creates an array from an enum variable in JavaScript, but it's looking a bit old and clunky. I'm curious if any JavaScript or jQuery experts out there have a cleaner (best practice) approach for achieving ...

Unable to change the visibility of blockquotes using jquery

Currently, I am delving into the world of basic JQuery functions. My main focus right now is figuring out how to display the active blockquote while keeping the others closed or closing them. Essentially, creating a toggle effect where only one blockquote ...

Exploring the interactivity of Vue3 Composition API props!

Currently, I am monitoring two props on a child component (basicSalaryMin and basicSalaryMax). Once the value changes, my next step is to update a reactive value on the parent component (data.companyModels, which is also passed to the child component as a ...

The hyperlink functionality is disabled because Javascript is set to return false

JS Fiddle Example When using the 'FOO' and 'BOO' items in the navigation bar to open dropdown boxes, I have implemented a code that closes them when a click event occurs outside. This code has been working fine as shown below: $(docum ...

Implement auto partial page refreshing in ASP.NET without using the UpdatePanel feature

Looking to implement auto partial page refresh in asp.net without sending excessive data through UpdatePanel. Considering using a webservice called by JavaScript instead, but unsure how to trigger it automatically rather than by button click event. Many e ...

Execute HTML code within a text field

Is it possible to run html code with javascript inside a text box, similar to w3schools.com? I am working solely with html and javascript. Thank you. For example, I have two text areas - one for inserting html, clicking a button to run the code, and displ ...

Utilize the toString function along with the substring method within an ejs template

I am attempting to showcase an employee's ID by displaying only the last four digits in a table on an EJS page. The data is stored in MongoDB and I am using Express for handling routes. Here is my Express route: app.get('/routehere', async ...

What is the method to retrieve the exact value of {match.params.id} in React Router?

This is an example of code that I have. However, I am unsure about how to extract the value and utilize it afterwards. class CustomView extends Component { componentDidMount() { var uniqueId = {match.params.id} } render() { ...

Having trouble with typecasting in Angular 9 after receiving an HTTP response?

When initializing my component, it fetches student information from an API. Here is the ngOnInit code for component-version1: ngOnInit(): void { if(!this.student) { this.studentsService.getStudentDetail(this.id).subscribe( (response: Stu ...

Disregard all numbers following the period in regex

I have developed a function to format numbers by adding commas every 3 digits: formatNumber: (num) => { return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,') }, The issue with this function is that it also add ...

What could be hindering the activation of my button click event?

Below is the js file I am currently working with: var ButtonMaximizer = { setup: function () { $(this).click(function(){ console.log("The maximize button was clicked!"); }); } }; $(docum ...

Taking a Breather with mywindow.print()

I'm currently utilizing a fantastic printing script that I found: <script type="text/javascript"> function PrintElem(elem) { Popup($(elem).text()); } function Popup(data) { var mywindow = window.ope ...

What is the best way to retrieve data from within a for loop in javascript?

Seeking assistance in Typescript (javascript) to ensure that the code inside the for loop completes execution before returning I have a text box where users input strings, and I'm searching for numbers following '#'. I've created a fun ...

Enhance the user experience with a personalized video player interface

I am facing difficulty in creating a responsive video with custom controls. While I understand that using a <figure></figure> element and setting the width to 100% makes the video responsive, I am struggling with making the progress bar also r ...

How can I access the id_lang variable in React JS from outside its scope?

How do I access the 'id_lang' variable outside of the render function in order to pass it down for checking? const Navbar = () => { const getID = async (id) => { let id_lang = id; console.log(id_lang); } ret ...

Setting up a Web application testing environment on its own

Embarking on my journey in web application development and testing, I am currently involved in a project that requires me to create a standalone environment for testing the web application. The main goal is to ensure the web application is easily testable ...

listening for events on nested classes

I am looking to dynamically toggle the class "collapsed" on each element with the class "category" when it is clicked. The issue arises when these "category" elements are nested within each other, causing the child elements to also trigger the class change ...

Leveraging Laravel 5.4 routes with AngularJS $http module

I'm working with Laravel 5.4 and AngularJS. Currently, I have a function set up like this: $scope.allPosts = function() { $http.get("/posts") .then(function(){ }, function(error){ }); }; Is there a way for ...