"Why is the success handler in the AngularJS controller not being triggered by the $http service

Currently, I am in the process of working on an AngularJS application. After creating the basic structure of the application, I moved on to implementing routing in Angular. This involved successfully setting up routing so that data from previous pages could be accessed on the page I redirected to using the $routeParams service.

Within my controller, I made a call to the $http service with input coming from the $routeParams. Despite seeing the response from the REST API in the network tab of Chrome, the success handler of the http service was not being triggered. I tried debugging the issue but couldn't reach the breakpoint.

Below is my routing configuration:

var app = angular.module('mainApp',['ngRoute']); 
app.config(function($routeProvider){
    $routeProvider.when('/',{
        templateUrl:"main.html",
        controller:'CategoriesController'
    }).when('/imagedetails/:imageId',{
        templateUrl: 'imagedetails.html',
        controller:'ImageDetailsController'
    })
    .otherwise({redirectTo:'/'});

});

Hence, I passed imageId to ImageDetailsController in order to fetch data from the REST API.

This is the controller code snippet:

 var ImageDetailsController = function($scope, $http, $routeParams)
    {
        $scope.imageId = $routeParams.imageId;
        console.log("Print image id : " + $scope.imageId);
        $scope.image = {};
        $scope.params = $routeParams;

         var downloadImageRequest = {
                 method: 'GET',
                 url: '<my-rest-api-url>',
                 headers: {
                   'Content-Type': 'application/json' 
                 }
        };

        $http(downloadImageRequest).then(onImageSuccess, onImageFailure);

        var onImageSuccess = function(response){ // i have put debug inside this method but never reaches controller
            console.log(response  );
            $scope.image = response.data.results[0];
        };
        var onImageFailure = function(response){
            alert("Failed to load image please try again!!");
             console.log(response);
        };
    }

The Network tab in the Chrome developer tool displays the response, however, the method where I set the response data is not being triggered.

If anyone can provide assistance, it would be greatly appreciated.

Answer №1

Before using your variables, make sure to define them properly. Remember that defining a variable is not the same as defining a function. Here are two ways you can achieve this:

    var onImageSuccess = function(response){
        console.log(response  );
        $scope.image = response.data.results[0];
    };

    var onImageFailure = function(response){
        alert("Failed to load image please try again!!");
         console.log(response);
    };

    $http(downloadImageRequest).then(onImageSuccess, onImageFailure);

Alternatively, you can define named functions like this:

    $http(downloadImageRequest).then(onImageSuccess, onImageFailure);

    function onImageSuccess(response){ // I have inserted debugging code within this function but it never reaches the controller
        console.log(response  );
        $scope.image = response.data.results[0];
    }

    function onImageFailure(response){
        alert("Failed to load image please try again!!");
         console.log(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

Creating an HTML webpage that contains scripts for handling responses in Node.js

I am a beginner in node.js and I'm attempting to display an html file named index.html which includes a reference to a javascript file called test.js: <!-- Content of index.html --> <html> <head> <script src="test.js">&l ...

The built-in functions of Wordpress are not able to be identified in the ajax PHP file

As a newcomer to Wordpress development, I am facing challenges with implementing ajax on my WordPress site. I am currently working on a plugin that requires the use of ajax. However, my php file (xxxecommerce.ajax.php) is not recognizing the built-in Word ...

Is there a way to universally retrieve the editing cursor's position for any active editor using JavaScript or a plugin?

While there are npm plugins available such as robotjs to obtain the mouse position, I have not been able to locate a similar plugin for globally retrieving the edit cursor position. I am currently developing a desktop application for Windows using the ele ...

Creating compressed files using JavaScript

I am currently working on unzipping a file located in the directory "./Data/Engine/modules/xnc.zip" to the destination folder "./Data/Engine/modules/xnc". Once I have completed writing to these files, I will need an easy method to rezip them! While I wou ...

Ways to prevent a particular link from functioning in HTML or JavaScript

Hey there, I am currently using a Gchat voice and video chat script. Check out my website if you're interested. The issue I'm facing is that someone logs into my chatroom and uses this flash link to crash other users' browsers. Whenever th ...

Unlock the Secrets of JavaScript Key Codes

I am currently dealing with a JavaScript routine that I did not create. This routine is triggered by the onkeydown attribute of a text box in order to restrict certain keystrokes. The first argument does not seem to have any significance. The second argum ...

Visibility of image changes after selecting from dropdown menu

Whenever I choose a language from the dropdown menu, the corresponding language image should display in a div next to it, while hiding the irrelevant images. I've been experimenting with CSS properties like display: none; and block;, as well as jQuery ...

Error: The function $.simpleTicker is not defined

Every time I try to call a jQuery function, an error shows up: Uncaught TypeError: $.simpleTicker is not a function I attempted changing $ to jQuery but it didn't resolve the issue. This represents my jQuery code: (function ($) { 'use ...

Tips for creating fonts that adjust depending on the length of characters

Is there a way to adjust the font size of a paragraph based on the space available in its containing div, depending on the length of characters? For instance: p{ font-size:15px; } <div class="caption"> <p>Lorem ipsum dolor sit amet, consect ...

Ways to display fresh information on webpage following data preservation in AngularJS

After saving some names in a form, I am attempting to display them alphabetically. Below is the method that contains all the saved data. The variable response.data should contain this data: function refreshNames() { NameService.getNames().then(func ...

Leveraging RSS feeds with JavaScript

I have a query regarding the use of Google Feed. It is assisting me in displaying RSS feeds through JavaScript. First, I will present the code and then I will pose my question. JavaScript Section: <script type="text/javascript" src="https://www.google ...

"Encountering distinct complications with CORS while working with Angular, Node, Express, Passport, and oauth2

I have developed an API for local authentication and Facebook authentication. For the authorization process, I am utilizing node, express, passport, and oauth2orize. The API is functioning perfectly when accessed through terminal applications and API tes ...

Is it possible to use HTML text as a CSS selector with JavaScript?

I've been searching for a solution to this issue but haven't found anything that works for me. Check out this code on jsfiddle. Person1 and Person2 both have class="from" and the CSS selector is .from so it applies to both. However, I want it ...

Tips for extracting value from a chosen input field without relying on its unique identifier

I am working on a simple code to help guess notes by ear. The concept involves tabs with empty input fields where numbers need to be entered based on a specific melody for the guitar fretboard. One button reveals the first note, while another button checks ...

Tips for creating a resolve service in $stateProvider within AngularJS

I'm looking for a solution to access a service while navigating to a different state with the use of State Provider in angular. ...

How can the label value be updated in a material ui slider component?

code snippet: https://codesandbox.io/s/runtime-worker-kxse3?file=/src/App.js Can anyone help me ensure that the labels in the bubble display the same values as the text (3, 5, 7, 10)? ...

Button within ng-switch statement

Issue with switch button inside switch statement, only functioning correctly outside of the switch statement. See below for my code: <div ng-controller="LoginController as LC"> <div ng-switch on="view.name"> <div ng-switch-de ...

Adjust focus upon the activation of another element or event

I have a tab-like view on my page with different events triggering the focus to one of the tabs. The events include clicking on the tab header, data load completion, and initial loading. While hiding and showing the div is straightforward using a model var ...

Dual Networked Socket.IO Connection

I have set up a node.js server with an angular.js frontent and I am facing a problem with Socket.IO connections. The issue arises when double Socket.IO connections open, causing my page to hang. var self = this; self.app = express(); self.http = http.Ser ...

Transform an array into an array of objects

I currently have a collection of words stored in a .json file Here is an example: [ "apple", "banana", "orange" ] My objective is to create an object for each word Similar to this structure: [ { word: "appl ...