What is the best approach to managing errors from an Angular service within controllers?

As a newcomer to Angular, I am trying to figure out how to access error messages from a service within my controller.

This is what my service looks like:

 admin.service('fileUpload', ['$http', function ($http) {
        this.uploadFileToUrl = function(file, uploadUrl){
           var fd = new FormData();
           fd.append('file', file);

           $http.post(uploadUrl, fd, {
              transformRequest: angular.identity,
              headers: {'Content-Type': undefined}
           })

           .success(function(response){
              console.log(response)
           })

           .error(function(response){
              console.log(response)
           });
        }
     }]);

And here's the upload function inside my controller:

admin.controller('uploadCtrl', function($scope, fileUpload){

 $scope.uploadFile = function(){
           var file = $scope.myFile;
           var uploadUrl = "/upload-url/";
           fileUpload.uploadFileToUrl(file, uploadUrl)
        };

});

Answer №1

$http.post is a function that returns a promise when called. By returning this promise from the uploadFileToUrl function, anyone needing to interact with the result can do so by using the promise object.

Service:

admin.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
       var fd = new FormData();
       fd.append('file', file);

     //VVVVVV----------  added return statement
       return $http.post(uploadUrl, fd, {
          transformRequest: angular.identity,
          headers: {'Content-Type': undefined}
       })
    }])

Controller

admin.controller('uploadCtrl', function($scope, fileUpload){
    $scope.uploadFile = function(){
       var file = $scope.myFile;
       var uploadUrl = "/upload-url/";
       fileUpload.uploadFileToUrl(file, uploadUrl)
         //VVVVVV------------ added .then and callbacks
           .then(
              function (result) {
                 console.log('success!');
              },
              function (error) {
                 console.log('error :(');
              }
           )
    };
});

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

AngularJS selectChosen does not have built-in support for translation

<select chosen options="myOptions" ng-model="StatCode" data-placeholder="{{'PleaseSelect' | translate}}" ng-options="item[0] as item[1] + ' / ' + item[0] for item in myOptions" required>< ...

Guide on transitioning from a WebGL renderer to a canvas renderer in three.js

My goal is to display a scene using either a WebGL renderer or a canvas renderer in three.js (version 69). This is the code I am using: <!DOCTYPE html> <html> <head> <script src="./libs/three.js"></script> <scri ...

How can I pass a specific value, rather than the entire array, in a ReactJS dropdown menu?

I am facing a problem where the entire array is being passed as an argument when I call onchange after getting correct values in the dropdown. Instead of only receiving the selected value, e contains the whole array. Here is the code snippet that demonst ...

Automatically fill in input fields in a form by selecting options from a dropdown menu and extracting data

After executing a MySQL query, a select dropdown menu is populated with data like this: <form method="post" action="action.php"> <select name="elements" id="elements"> <option type="text" value="">Select an element to be modifie ...

Retrieving Specific Node Value in Array From XML Document

In my JavaScript function, I have a variable named "result". The value of the variable "result" is an XML. I need to create an array containing only the values of the opportunityid (highlighted in the image). How can I extract the particular node value ...

Displaying decimal values in Angular as percentages

In my Angular application, I have a numeric textbox that displays a percentage value and allows users to update it. https://i.stack.imgur.com/eCOKe.png <label for="fees">Fees %</label> <div class="inpu ...

Retrieving the value of an object based on a dynamic key in Typescript

Currently, I am facing an issue with exporting a single value from a configuration object based on the process.env.NODE_ENV variable. Specifically, I am attempting to retrieve the value of the configEnvs variable like this: configEnvs['local']. H ...

Combining two forms into one PHP page, but intending to submit only a single form

I'm facing an issue on my page where I have both a sign-in and a sign-up form. Whenever I click on either the sign-in or sign-up button, it always ends up submitting the sign-up form. What am I doing wrong? Here's the PHP code snippet: if($_SE ...

How can I incorporate a fade opacity effect into my Div scrolling feature?

I successfully implemented code to make div elements stick at the top with a 64px offset when scrolling. Now, I am trying to also make the opacity of these divs fade to 0 as they scroll. I am struggling to figure out how to achieve this effect. Below is ...

Using Google App Script to transfer specific columns of a row to a different tab based on the value in a particular column

I have a script that moves rows based on a specific value in a column, but I am looking to only transfer certain columns within those rows. This is the current script I am using: //Script to move rows from Form tab to Des tab function moveSafeRows() { v ...

I'm looking for a method to trigger onChange() specifically on Internet Explorer using only JavaScript, HTML, and CSS without relying on jQuery

Looking for a way to utilize onChange() only on Internet Explorer using Javascript, HTML, CSS (No Jquery). My current code successfully sends the input to my function upon onChange(), but it seems to work smoothly on Chrome and not on IE. Is there a meth ...

Incorporate my personalized icons into the button design of ionic 2 actionSheet

I'm struggling to figure out how to incorporate my personal icon into the actionSheet feature of ionic 2/3. presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Mode', buttons: [ { ...

Ways to verify the $window variable in ng-if or ng-show

One variable named variable1 has been declared, and I am looking to validate this variable across all pages using ng-if or ng-show. ...

Onload, capture page elements, delete them, and then access the original content

I am encountering two DIV elements on my page that I need to capture upon loading the page and preserve their contents until the page is refreshed. The nested DIV element is contained within the other one. After locating these elements initially, I want t ...

Setting up a custom destination for installing a NuGet package

I recently created an ASP.NET 5 application in Visual Studio Community Edition. I attempted to add the nugget package angularjs.TypeScript.DefinitelyTyped using the command Install-Package angularjs.TypeScript.DefinitelyTyped and also through the NuGet Pac ...

How can one access this completely anonymous entity, and is there a way to identify it?

Similar Question: Understanding the Purpose of a Script Tag with src and Content While browsing through this webpage that explains how to include Google's +1 button, I came across an example code snippet that caught my attention: <script type ...

Displaying a variable in a live HTML user interface

I have successfully created a Python program that captures data from an Arduino Potentiometer and shows it on the Python console. Now, I am working on enhancing the output by displaying it in a local HTML file. I am seeking guidance on how to incorporate t ...

The media parameter seems to be malfunctioning when attempting to send it to the Kaleyra API using code

Attempting to send media through the Kaleyra API using my code is proving unsuccessful. However, when I make the same request via Postman, it works perfectly fine. async whatsappAPIWithAttachment(requestBody) { let api_key = ""; if (requ ...

Character count in textarea does not work properly when the page is first loaded

As English is not my first language, I apologize in advance for any grammar mistakes. I have implemented a JavaScript function to count the characters in a textarea. The code works perfectly - it displays the character limit reducing as you type. However, ...

Examining an array to identify palindromes

Is there a way to loop through an array and check if each word is a palindrome, instead of manually passing an argument for each word? If a word is a palindrome, return the word; otherwise, return 0. var myArray = ['viicc', 'cecarar', ...