transmitting error messages from a service to a controller in AngularJS

Controller.js

var vm = this;
vm.admin = {};

vm.add = function () {
    API.addAdmin(token, vm.admin)
        .then(function (resp) {
            vm.hideForm = true;
            vm.showButton = true;
            Notify.green(resp);
        }, function (resp) {
            Notify.red(resp);
        });
};

API.js

function addAdmin(token, dataObj) {
        return Constant.getApiUrl()
            .then(function (url) {
                $http({
                    method: 'POST',
                    url: url + '/client/admin',
                    headers: {
                        'Token': token
                    },
                    data: dataObj
                }).then(handleResp);

                function handleResp(resp) {
                    var responseStatus = (resp.status >= 200 && resp.status < 300) ? 'good' : 'bad';
                    if (responseStatus === 'good') {
                        console.log("Success" + resp);
                        return resp;
                    } else {
                        console.log("Failed" + resp);
                        return resp;
                    }
                }
            })
    }
  1. To determine the response status from the API as either success or error, you need to evaluate it in your controller by connecting it to the corresponding success or error functions.

  2. If possible, avoid passing the successfn and errorfn from your controller to the API unless there are no other alternatives available.

  3. You should receive the response data from the API into your controller and display it in a Notify message.

Thank You!

Answer №1

When using a certain service (assign response values to "originalData"):

angular.module('appname').service('myserviceName', function(yourExistingService){
          this.myFunction= function(originalData) {
         //Make sure to return promise from your addAdmin method for the next line to work.
          var promise =  yourExistingService.getResponseFromURL(originalData);
                           return promise;
             }                         
         }); 

In your controller, use the following code :

var promise = myserviceName.myFunction($scope.originalData);
              promise.$promise.then(function() {
                         console.log($scope.originalData);                                 
                     });

You can then inspect your "originalData" and write additional code as needed. For more information, refer to: .

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

Angular.js has been activated with the chosen:open event

I've been implementing the chosen directive for AngularJS from this source and so far it's performing admirably. However, my goal is to trigger the chosen:open event in order to programmatically open the dropdown menu as outlined in the chosen do ...

What is the best way to fix the Syntax error that reads "Unexpected token (1:13)"?

I can't seem to figure out why my code keeps showing errors in the browser. I'm still new to coding and learning slowly, with help from knowledgeable individuals on stackoverflow :) Card 1.jsx Syntax error:() Unexpected token (1:13) > 1 | i ...

Apply a specific style conditionally using Angular's ng-repeat directive

Currently, I am utilizing ng-repeat to iterate through a list of divs and manually adding items to the JSON that is rendering these divs. My goal is to position the last div that I add in the JSON at the location where the mouse cursor is, while keeping th ...

Converting an unbroken series of string values into organized key-value pairs for easy reference

I assure you this is not a duplicated question. Despite my attempts with JSON.parse(), it seems to be ineffective. Here's the issue at hand: I recently received assistance from an answer that was both crucial and enlightening. However, the code prov ...

Exploring the possibilities of working with deeply nested components in React recursively

I have a basic to-do list with functionality for adding todos, toggling completion status, and deleting todos. My goal is to have the ability to nest todos infinitely. I've been able to display nested todos through recursion, but I'm struggling t ...

Converting counterup2 to pure vanilla JavaScript: step-by-step guide

Is there a way to convert the counterUp2 jQuery code to vanilla JavaScript? const counters = document.querySelectorAll('.counter'); function count(element) { let currentValue = 0; const targetValue = parseInt(element.innerText); let interv ...

Managing uncaught exceptions in node.js

While working on my project, I encountered an issue with catching exceptions when opening a connection using mongoose.createConnection. Here's the code snippet causing the problem: var createdDb = mongoose.createConnection(connectionString); createdD ...

What is the best way to create a list from a matrix using JavaScript?

I have an array structured as follows: const input_array= [ ["red", "green"], ["small", "medium"], ["x", "y", "z"] //... can have any number of rows added dynamically ...

How can you prevent videos from constantly reloading when the same source is used in multiple components or pages?

How can we enhance loading performance in Javascript, React, or Next JS when utilizing the same video resource across various components on different pages of the website to prevent unnecessary reloading? Is there a method to store loaded videos in memor ...

The operation to set a nickname in Discord.js was unsuccessful due to insufficient permissions

Recently, I started using discord.js to create a simple bot. Whenever I try to change the nickname by calling message.member.setNickname("Another Nickname").then(console.log, console.log); I receive the following error message: { name: ' ...

use element ui tree and vue to filter files according to selected folder

Utilizing the element UI treeview to showcase folders. Each folder or its child folder contains files that need to be displayed based on folder selection. While it's easy to filter and list out these files in a normal list, I am facing challenges with ...

Steps to implement an image zoom function triggered by a button click

I'm working on a school project that requires me to use only html, css, and javascript for creating a website. Currently, I'm designing a landing page with a button that will navigate the user to another page. My goal is to have the background im ...

Establishing the httppostedfilebase variable when validation is unsuccessful in an ASP.Net MVC view

I'm currently facing an issue with handling validation errors in my application. I have implemented uploading and downloading images successfully, but when there are validation errors and the controller redirects back to the page, the HttpPostedFileBa ...

Updating ng-model with the values from a property in a collection in AngularJS

Encountering an unusual problem with setting the ng-model for a select drop-down menu. Despite using a property value that matches one in the ng-options, the ng-model consistently ends up as null. Below is the function responsible for fetching orders: o ...

Specification for Application Input: Receiving input information for a specific method

Is there a recommended method for visually representing the input data structure required for a server application? I am working on specifying the correct input data that the server will receive via an http post request. The data being sent is a complex js ...

Find the identifier that does not currently exist in the collection of objects

There is a situation where I have an array and an object that consists of arrays of ids, which are essentially permission objects. My goal now is to extract the ids that do not exist in the given object. Can someone assist me with devising the necessary l ...

The Helper Text fails to display the error, and the error message does not appear when the login data is incorrect

Currently, I am facing an issue with displaying error messages within my helper text component while using Material UI. Despite successfully testing my backend code using Postman to identify errors, I am unable to see the error message under the button whe ...

Accessing UPI apps such as Google Pay through deep linking from a web application

I am currently exploring the possibility of deep-linking to individual UPI apps, like Google Pay, that are installed on a user's phone. The goal is for users to be seamlessly redirected to their preferred UPI app when they click on the respective icon ...

Using yargs to pass parameters/arguments to a Node script through an npm script

Is it feasible to retrieve a key from yargs when utilizing as an npm script argument? A user inputs in the OSX terminal: npm run scaffold --name=blah which triggers in package.json: "scaffold" : "node ./scaffold/index.js -- " This leads to const yar ...

The predicament encountered with user registration in the realm of Node.js

I am encountering a problem with the sign-up route in node.js and MongoDB. Whenever I attempt to post data using Insomnia, it displays an error message. You can find the screenshot of the error [here](https://i.stack.imgur.com/qnGAv.png). Here is the code ...