Angular dependency injection function

What is the best placement for the common handleError and handleSuccess functions?

These functions are commonly used by every service. Where should these functions be placed? Should they be global functions injected as dependencies?

(function () {
    "use strict";
    angular.module('myApp.Group')
        .service('GroupService', function ($http, $q, $location, Environment) {



            // I transform the error response, unwrapping the application data from
            // the API response payload.
            function handleError(response) {

                // The API response from the server should be returned in a
                // normalized format. However, if the request was not handled by the
                // server (or not handled properly - ex. server error), then we
                // may have to normalize it on our end, as best we can.
                if (!angular.isObject(response.data) || !response.data.message) {
                    return ($q.reject("An unknown error occurred."));
                }

                // Otherwise, use the expected error message.
                return ($q.reject(response.data.message));

            }


            // I transform the successful response, unwrapping the application data
            // from the API response payload.
            function handleSuccess(response) {
                return (response.data);
            }

            this.remove = function (id) {
                var request = $http({
                        method: "delete",
                        url: '/group/' + id
                    });
                return (request.then(handleSuccess, handleError));
            };
        });
}());

Answer №1

Here is our approach:

We utilize the $httpProvider to capture the responses and handle each code individually. We have created a service specifically for this purpose.

This is how our application configuration appears:

appModule.config(['$routeProvider', '$locationProvider', '$httpProvider', '$provide',
function ($routeProvider, $locationProvider, $httpProvider, $provide) {
    // HTTP interceptor to manage session timeouts and basic errors
    $httpProvider.responseInterceptors.push(['httpHandlersSrv', function (httpHandlersSrv) {
        return function (promise) { return promise.then(httpHandlersSrv.success, httpHandlersSrv.error); };
    }]);
    routeProvider = $routeProvider;
    $locationProvider.html5Mode(true);
}
]);

Below is the implementation of our $httpHandlersSrv where we address errors. Note that we simply pass successful responses without any modifications:

angular.module('appModule').factory('httpHandlersSrv', ['$q', '$location', '$rootScope', 'toaster', '$window', function ($q, $location, $rootScope, toaster, $window) {
return {
    success: function (response) {
        return response;
    },
    error: function (response) {
        switch (response.status) {
            case 0:
                // Actions to take when a response is not received
                break;
            case 401:
                // Handling authorization errors
                break;
            case 400:
               // Handling other types of errors
                break;
            case 500:
               // Dealing with server errors
                break;
            default:
                // Managing other error codes
                break;
        }
        return $q.reject(response);
    }
};
}]);

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

Guide on displaying JSON information upon clicking using JavaScript

I'm having difficulty writing the logic for this code. I have extracted data from a vast API. The current code fetches all program titles (some may be repeated) and compares them with an array of late night shows, then displays them once in their own ...

Receiving the outcome of an asynchronous function in JavaScript

async function retrieveKey() { try { var key = await dec.awsDecrypt('dev-frontend') return key; } catch(err) { } } //calling the function const result = retrieveKey() In the code snippet above, there is an asynchronous ...

Incorporate axios within getStaticProps while utilizing Next.js

I am working on a new project where I am utilizing axios to handle request data. However, I am facing an issue when using axios in the getStaticProps function which results in an error on my index.js page. Here is a snippet of my index.js code: import ...

Retrieve data from the table and dropdown menu by clicking a button

A script is in place that retrieves data from two columns (Members, Description) dynamically from the table upon button click. Table html Here is the JQuery code responsible for extracting values from the table: $(function() { $('#myButton') ...

I'm running into some issues with flexbox and I'm in need of some assistance to find

I positioned two divs next to one another, but instead of each taking up 100vw, they are both sharing 50% of the available space. Is there a solution for this issue? Thank you. Page Image import type { AppProps } from "next/app"; import "./global.cs ...

ClickEvent (or element selector) is experiencing functionality issues

I'm currently working on creating a small calculator using HTML, CSS, and JS. However, I'm facing an issue with selecting buttons of the calculator from the HTML script and adding EventListeners to them. Here is a snippet of my HTML code: `< ...

Verify if the property in every element of the array is not empty

How can you determine if all employees have a non-null value for the SSN property in the given object? Employees: { id: 0, name: "John", SSN: "1234" } { id: 1, name: "Mark", SSN: "1876" } { id: 2, name: "Sue&q ...

Passing the unique identifier of a record in NextJS to a function that triggers a modal display

I'm currently facing an issue with my NextJS component that displays a list of people. I have implemented a delete button which triggers a modal to confirm the deletion of a person, but I am struggling with passing the id of the person to be deleted. ...

Understanding the process of retrieving a data value from HTML in an AngularJS directive

I'm a beginner with Angular and I'm trying to pass some data to my angular directive from the template. <div class="col-md-6" approver-picker="partner.approverPlan.data" data-pickerType="PLAN"></div> I h ...

Using JQuery to pass a concatenated variable

What is the reason behind the success of this code: $(".ab").css({'background':'#ce0000','color':'#EEE'}); While this code does not work: f("ab"); function f(ab){ var x = '".'+ ab +'"'; ...

Customizing CoreUI column names in Vue

I am working with an array of item objects for a table. For example: [{ name: 'Sam', age: 24 }] Instead of using the default column names like age, I want to set custom field names. For instance, I want to display the column as Id instead of age ...

Issue: The component series.line does not exist. Please ensure it is loaded before using it in Vue Echarts

I added the line component, but I'm still encountering issues. I set up my project using vue cli 3 and referred to this guide, but I can't locate the vue.config.js file in my project. Therefore, I manually created a vue.config.js and placed it in ...

Embed Javascript Code Within Text Field

Is there a way to incorporate this JavaScript into the "price" text value? Below is the code snippet: <script> function myFunction() { var x = document.getElementById('car-select')[document.getElementById('car-selec ...

Using JQuery to manipulate `this`, its children, its siblings, and more

Can anyone help me determine the most effective way to send data from a get request to a specific div? My challenge is to send it only to a div that is related to the one triggering the action. For example, when I click on the message_tab, I want to send t ...

What is the process for customizing the default animation in the Dialog component?

Currently I am utilizing the Material UI framework and looking into modifying the default animation for a Dialog opening. Specifically, I would like the Dialog to appear from bottom to top when it opens up. Any suggestions on how this can be achieved? Ap ...

A guide on organizing nested JSON objects in JavaScript

I am currently using JavaScript to retrieve JSON data that looks like this: [{ "data": { "serialNumber": "12345678", "loopCount": 2, "temperature3": 22.74921781259558, "temperature2": 21.459065450414467, "temper ...

The event.pageY position consistently reflects the laptop screen size rather than the exact position where the click occurred

My webpage is scrollable, but the event.pageY position always corresponds to my screen size. Even when scrolling down and clicking near the top of the screen, it registers as 50px. I am currently utilizing event.pageY While this functions correctly on a ...

What are some ways to prevent having to constantly check for the existence of an object within another object when working

<template> <img :src="user.avatar_thumbnail"> <a :href="user.profile.link"/> </template> <script> export default { data: function () { user: {} }, ...

The Facebook SDK fails to activate in Internet Explorer

I am currently working on implementing a Facebook login using the JavaScript SDK. Everything is functioning correctly in most browsers, but I am experiencing issues with certain versions of Internet Explorer. The login functionality is not working on my l ...

Uploading images with Laravel and VueJS

I am having trouble with Vuejs image upload. My backend is Laravel, but for some reason the images are not being sent to the Controller. <form method="POST" class="form-horizontal" role="form" v-on:submit.prevent="updateProduct(editProduct.id)" en ...