Having trouble retrieving a value from the $http promise, causing the code within the then() function to not run as expected

In the past, I encountered a challenge with the $http service which I managed to solve by creating a dedicated service for handling my requests. However, as my requests grew larger, this solution started to seem inefficient. Instead of just assigning a simple word from the response to a $scope value, I now need to store an entire JSON configuration in the $scope.

Although I grasp the concept of promises and understand that the value returned by $http is initially null until the response arrives, the configuration I am working with is not extensive, yet I never seem to receive a response. Even when I display the variable holding the value on the view, it remains unchanged when the function is triggered.

Here is the code:

View

...
<div>
    {{loadedConfig}} 
</div>
<button ng-click="loadconfig()">load</button>

Controller

app.controller('ConfigurationCtrl', function ($scope, $rootScope, configloader) {
    ...
    $scope.loadedConfig = 'noconfig'
    $scope.loadconfig = function() {
        configloader.load().then(function (response) {
            $scope.loadedConfig = response.data;
        });
    };

Factory

angular
    .module('app')
    .factory('configloader', configloaderFactory);

function configloaderFactory($http) {

   var service = {
      load: load
   }

   return service;

   function load() {
      return $http.get('url/config');
   }
}

When I try making a simpler request, everything works fine. I've experimented with various other methods like $q.deferred, success()/error(), or even implementing a custom sleep() function but nothing seems to work. Is the code inside the 'then' supposed to execute once I receive the response? (I assume so, but it never does).

Thanks

Answer №1

Consider returning the promise from your factory, similar to the following example:

function fetch() {
     var promise =   $http.get('url/data').then(function(response){
         return response.data;     
     }, function(error){
         //handle error     
         return error;
     });
     return promise;
}

Answer №2

If you are dealing with lengthy requests, it would be wise to update your code by implementing a timeout feature:

return $http({
    method: 'GET',
    url: 'url/configuration',
    timeout: 1 * 60 * 1000    // setting a timeout of 1 minute
});

Answer №3

Here is a quick solution:

angular
    .module('app')
    .factory('configloader', configloaderFactory);

function configloaderFactory($http) {

   var service = {
      load: load
   }

   return service;

   function load() {
      return $http.get('url/config')
      .then(requestSuccessful)
      .catch(requestFailed)
   }

   function requestSuccessful(response) {
        return response.data;
    }

   function requestFailed(error) {
        console.log('Error', error.data)
    }

}

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

"An intermittent error is occurring with the jQuery webcam plugin, where a TypeError is being thrown stating that

Many times, I encounter the error stated in the subject line. The code snippet where this error occurs is within the else section of the function below: if ($('#clicktosnap').is('.disabled')) { alert ("Please enable the camera first, ...

Encountering an error in Laravel 5.1 and Vue.js - Error code 21678: Uncaught TypeError: Unable to retrieve 'data' property from null

Recently, while working on my Laravel and Vue.js application, I encountered an issue. Everything was running smoothly until I added another component following the same procedures as before. Suddenly, the data stopped displaying in the table, and I started ...

Why does this image slider begin with blankness?

For my recent school project, I created an image slider. However, upon starting the page or reloading it, only the arrows and dots are displayed. View screenshot of the issue Below is the code snippet: // JavaScript function to control the slideshow sho ...

Navigate to a fresh HTML page upon form submission

I'm completely new to the world of web apps and JavaScript, and I'm facing an issue where my form submission doesn't redirect me to a thank you page. Instead, it just leads to a blank page every time. I've tried researching solutions on ...

Refresh the custom JavaScript dropdown list without having to reload the page

I implemented this code to customize a drop-down list Selector. Is there a way to reset this code without reloading the page, maybe by triggering a function with a button click? <button onclick="reset();">Reset</button> For example, if "Jagu ...

Using touch-action to enable movement from the last item to the first item in HTML/C

Currently, I am utilizing the touch-action property in my carousel which auto slides without any issues. However, I am facing a problem where when I scroll using touch-action, it stops at the last slide instead of looping back to the first slide. My goal i ...

Place a <script> tag within the Vue template

I am currently developing an integration with a payment service. The payment service has provided me with a form that includes a script tag. I would like to insert this form, including the script tag, into my component template. However, Vue does not allo ...

Turning an array of strings into a multidimensional array

I have a JavaScript string array that I need to convert into a multidimensional array: const names = [ "local://john/doe/blog", "local://jane/smith/portfolio", "as://alexander/wong/resume" ]; The desired output sh ...

Issue: Firebase.update was unsuccessful due to NaN being present in a property within the first argument

A project I'm working on involves creating a web app where users can nurture a virtual tree. One of the key interactions is when the user fertilizes the tree, the "fertilizer" attribute should increase. However, an error keeps popping up stating that ...

Chromium is having issues with updating the dynamic source attribute

One portion of my script that pertains to the question is as follows: <script type="text/javascript> function handleImageClick() { var image = $("#image_id"); $(image).attr("src", "ajax-loader.gif"); $.ajax({ ...

What steps do I need to take in order to successfully make a checkbox?

I am attempting to use Angularjs to set a checkbox to true. When saved, it should store an integer value (1 or 0) in my field. Below is the code snippet for the view: <input type="checkbox" ng-model="lis.SMSPromotion" id="SMSPromotion" ng-init="checke ...

I am currently encountering an issue with a code snippet that is not performing as anticipated and require clarification

import React, {useEffect, useState} from 'react'; export function App(props) { let [state, setState] = useState(2); console.log('outside', state); useEffect(()=>{ document.querySelector('.btn').addEventListener( ...

The element is not positioned correctly due to the absolute positioning

This is my first attempt at creating a jQuery plugin and I have almost got it working correctly. You can view the example here. I've been struggling for days to position an element as desired. The goal is to display some text with an optional downwar ...

How to enhance a jQuery tab control by implementing custom JavaScript forward and back arrows?

Although there are other questions related to this topic, mine is unique. I have a scrolling jQuery feature that utilizes tabs for selection and is automated. Modifying the layout is challenging because it is dynamic and depends on the number of items in t ...

Angular animation not firing on exit

I am encountering an issue with my tooltip component's animations. The ":enter" animation is working as expected, but the ":leave" animation never seems to trigger. For reference, here is a link to stackblitz: https://stackblitz.com/edit/building-too ...

What steps should I take to ensure that this modal remains persistent?

I am searching for a method to keep this modal persistent even after it appears. Currently, the user can easily close it by clicking outside of the div. <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title ...

There are multiple ways to extract a value from Python code and assign it to a JavaScript variable in a JS file

I am currently working on developing the frontend for a voice bot using JavaScript, while the backend is written in Python. if hi == 0: talk('hello iam kavi') print('hello iam kavi Voice assistant') talk('How are you bu ...

Jasmine Timeout issue

Currently, I am in the process of writing a karma unit test script. Everything seems to be going smoothly, but unfortunately, I am encountering an error: Chrome 39.0.2171 (Windows 7) Unit: common.services.PartialUpdater Should be loaded with all dependenc ...

Understanding jest.mock: Verifying the invocation of a nested function

I have a section of code in my application that looks like this: import validationSchema from "./../_validation/report"; const reportModel = require("../models/report"); ctrl.addReport = async (req, res) => { const { body } = req; try { cons ...

ExpressJS route handler encounters an error due to undefined 'this' reference

teamList.js class teamListCtrl { constructor() { this.data = "example"; } fetch(response, request) { console.log("DISPLAY ! ", JSON.stringify(this)); } } module.exports = new teamListCtrl(); //singleton router.js var express = require( ...