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

Choose an item from a list that does not have a particular class

Here is a list of items: <ul id='myList'> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li class='item-selected'>Item 4</li> <li>Item 5</li> & ...

Creating two variables that share an identical name

Can variables with the same name set outside of a function be called within the function? var a = $(window).width(); // This is the variable I want to call if(!$.isFunction(p)){ var a = $(window).height(); // Not this one alert(a); } FIDDLE ...

Leveraging Angular2 within Angularjs framework

Can Angular2 be integrated with AngularJS? For instance, is there a way to have a button in an AngularJS application that, when clicked, shows an Angular2 form? What would be the best approach for this scenario? Would it be better to host them on separat ...

Utilize $resource to send information through a POST request

DEMO: http://jsfiddle.net/rob_balfre/7QUUf/ What is the best way to send POST data (across domains) using $resource in AngularJS? An example of successfully writing to the API using curl: curl --dump-header - -H "Content-Type: application/json" -X POST ...

Setting the default value in a Selectbox when utilizing two arrays with Angular

I created a customized control using data retrieved from an external source. var field= { "attributeName": "Country", "dbColumnName": "location", "fieldType": "DROP_DOWN", "optionName": ['US', 'AUS&a ...

Retrieving data from a radgrid with the power of jQuery

Trying to extract the text from the label GetName in a radgrid using jQuery. Need to iterate through each record to check the value of the label. Can anyone provide assistance? Thanks! Below is the code for my radgrid. <telerik:RadGrid ID="Gridview1 ...

Interactive planetary visualization using three.js in real-time

As I work on my react project, I'm developing a globe and looking to initialize it accurately with respect to a specific time, whether it be the current time or a future time. The goal is for this globe to correctly align itself with the day and night ...

Error: Client was unable to process JSON data

My server setup looks like this: var http = require('http'); //Defining the port to listen to const PORT=8092; //Function that handles requests and sends responses function handleRequest(request, response){ response.statusCode = 200; ...

AngularJS end-to-end testing using Testacular causes browser disconnections for all tests

I'm currently working on setting up e2e tests for my AngularJs project using testacular. I've successfully launched a node.js-based web server and can see the files being sent when a URL is loaded. I am also able to view the expected results in m ...

Is there a way to display a PHP error message while submitting the form asynchronously?

Utilizing phpMailer in combination with AJAX to send emails. The objective is to send the email and then showcase any error messages from submit.php on contact.php Currently, every submission displays "Message sent" even if it was not actually sent. Con ...

Achieving a sticky scrollbar effect in CSS/JavaScript for scrolling within nested divs

I am trying to create a table with vertical scrolling for the entire table content. Additionally, I need two columns within the table to be scrollable horizontally, but the horizontal scrollbars disappear when the vertical scrollbar is present. How can I k ...

Is it possible to incorporate Vue and Vuetify into an existing project that requires IE compatibility?

Currently in the process of enhancing a legacy project with new functionality. The front end is currently relying solely on jQuery for all the webpages. I have been tasked with adding another webpage and would like to incorporate Vuetify + Vue due to the i ...

Utilize Vue.JS to showcase JSON information from an external file

Currently, I have a View.JS app that displays a conversation thread from a JSON file. The existing code appears as follows: const app = new Vue({ el: "#app", data: { messages:[ { name: "Support", message: "Hey! Welcome to suppo ...

Setting up your own local Jquery Mobile Angular Adapter Todo app is easy and seamless

Currently, I'm in the process of familiarizing myself with the jQuery Mobile Angular adapter by configuring a local repository for the Todo app JSFiddle that is linked on the Github repository: http://jsfiddle.net/ocdemo/UM5Mr/ I am utilizing the "s ...

Can I store a large batch of images in one location and retrieve them using a REST API?

So here's the situation: I currently have a large collection of images saved on my Mac. I'm working on a landing page that resembles an ecommerce deal site. Manually inputting the src url for each of the thousand pictures would be incredibly tim ...

Is there a way to remove a dynamically rendered component from a list?

Whenever I click a button, the same component is dynamically rendered on top of the list. But now, I need to implement a feature where users can delete any component from the list by clicking a cancel button associated with each component. Here's my ...

Create a variety of unique objects on the canvas without any repetition or unwanted overlapping

Is there a way to generate objects on a map in a HTML5 Canvas without them overlapping or occupying the same space? I tried checking inside an array to see if the next 20 values are already taken to prevent overlapping, but it didn't work as expected ...

Objects may unexpectedly be sorted when using JavaScript or Node.js

When I execute the following code using node app.js 'use strict'; var data = {"456":"First","789":"Second","123":"Third"}; console.log(data); I am receiving the following output: { '123': 'Third', '456': 'F ...

Imagine a complex JSON structure with multiple levels of nesting

Take a look at this JSON data : { department_1 : [{ id : 1, name = Joe Smith, email : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="660c150b0f120e2613150048030213">[email protected]</a>}, ...., { id : 500, name ...

Display JSON data in a dynamic d3.js visualization

Using d3.js, I have created a chart that displays weekly scores when hovering over the months. To view the chart, click here: https://jsfiddle.net/qp7L1hob/1/ In my database, I maintain a table called Table pointsScored where I keep records of employee s ...