Angular promise did not assign a value to a variable

Can someone assist me with a problem I'm facing? After the first callback, the variable doesn't seem to change as expected. Below is my code snippet:

    this.handlerLocalDef = function(defer) {
        var hash = {};

        defer.then(
               function(response) {
                   hash = response;
               },
               function(err) {
                   showPopup(err);
               }
        );

        return hash;
    };

    var initialized = function()  {
        var localRegDef = Localization.getLocalizedDefer('regularform'),
            localPaymDef = Localization.getLocalizedDefer('payment');

            localizeRegForm = self.handlerLocalDef(localRegDef);

            $timeout(function() {
                console.log("localizeRegForm", localizeRegForm);
            }, 5000);
   }();  

Upon checking the console log, it shows `localizeRegForm: {}`

Answer №1

Simply assigning hash = response only changes the reference of the local variable, not the original object itself. To properly update the original object with the values from response, you can use angular.extend(hash,response);. This will effectively copy all members of response into the hash object, ensuring that the receiver sees these changes.

Note: Be aware that this method may not work for primitive values (strings, numbers, booleans, etc.) or arrays.


Here is a fiddle showcasing the suggested approach: http://jsfiddle.net/sVRCg/3/


If you have concerns about how to verify that hash has been extended with response, using polling like setTimeout is not ideal. Consider returning a promise instead to accurately track when the response is ready.

Alternatively, explore implementations similar to how ngResource handles this process, although it may involve more complexity in the code structure.

Answer №2

Async programming should not involve setting arbitrary timeouts and hoping for data at a specific point in time. It's important to use deferred objects as intended and utilize callbacks for more reliable functionality. Here is a suggestion on how you can restructure your code to ensure it works properly, although effectiveness may vary based on your unique circumstances:


    this.handlerLocalDef = function(defer,callback) {

        defer.then(
               function(response) {
                   callback.apply(this,[response])
               },

               function(err) {
                   showPopup(err);
               }
        );

    };



    var initialized = function()  {
        var localRegDef = Localization.getLocalizedDefer('regularform'),
            localPaymDef = Localization.getLocalizedDefer('payment');


            self.handlerLocalDef(localRegDef,function(response) {
                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

Angular JS does not display the bold tag for specific words

I'm currently working on an Angular JS application and receiving text from the server that needs to be displayed on my website. The text received from the server is: "My name is <b> John </b>" with b tags. Unfortunately, when I display ...

What is the best way to implement a Fibonacci sequence using a for...of loop?

**Can someone show me how to generate Fibonacci numbers using the for...of loop in JavaScript?** I've tested out the following code and it's giving me the desired output: function createFibonacci(number) { var i; var fib = []; // Initi ...

What Causes the Misalignment Between My Image and Text?

I am trying to randomly select a slide from the list of slides when the page loads, and then display it in the hero section of a website. However, I am facing an issue where the Image seems to be out of sync with the Text & Button (for example, displaying ...

Utilize ng-repeat to display a series of images, with the first image being placed within a unique div

My challenge lies in displaying product images using ng-repeat, where one image is located in a separate div. Let me share my code and explain what is happening. The API response provides product details and images [{"id_product":"1000","name":"Nikolaus ...

What is stopping me from sending data via POST - Express?

I'm encountering an issue with Express [POST request]: I have developed server-side and client-side code to send data to both the terminal and the browser.. Unfortunately, I am unable to view the result of the post function!! Please assist me, I feel ...

Is there a way to avoid adding this final "faulty state" to the array?

While working on dynamically slicing an array, I noticed that my while loop was causing an extra slice to be added when it broke the conditional. Even though I can achieve the desired functionality by removing the last element with arr.pop(), I am curious ...

Triggering a loop error may occur when attempting to update the state based on a

What I want to achieve is updating the state with the value received from a child component. However, whenever I try using the setstate method in my function, it results in a looping error. Here's a snippet of my code: class ParentTab extends Compone ...

Utilize ExpressJS app.use to enable middleware functionality

As I delve into learning ExpressJS, my attention was drawn to a particular code snippet that has left me puzzled. The function app.use is perplexing me and the documentation isn't providing clear insight. Could someone shed some light on what exactly ...

Link the <select> element with ng-options and ng-model, ensuring that the model contains a composite key

I am facing a challenge with my Angular service that retrieves a list of objects with a composite key comprising two parts. I am struggling to write the bindings in a way that properly re-binds existing data. Below is my current attempt: angular.module( ...

Struggling to effectively transfer a callback function within a series of functions

I am currently utilizing the codebird library to make requests to the Twitter API. The responses from these requests are functioning as expected, but I am looking to pass that response along to my route. Below is a segment of my route.js: router.get(&apos ...

React Express Error: Unable to access property 'then' of undefined

I'm facing an issue while trying to server-side render my react app for users who have disabled JavaScript and also for better search engine optimization. However, I am encountering the following error: TypeError: Cannot read property 'then' ...

Utilizing Angular 6 and JavaScript to invoke two functions within an (ngClick) event in both the Component and JavaScript

I have a requirement to execute two functions in my click event, one for my component and the other for a custom JavaScript function. Here is the code snippet: Angular click event: <button type="button" class="btn btn-primary" (click)="Plans(); " [att ...

How to retrieve an element in jQuery without using the onclick event listener

I'm looking to extract the element id or data attribute of an HTML input element without using the onclick event handler. Here is the code I currently have: <button class="button primary" type="button" onclick="add_poll_answers(30)">Submit</ ...

React frontend communicating without backend server

Is it possible to send a message between two frontend users on web applications built with React? ...

I'm struggling with a namespace conflict in Javascript - how can I access this value in the function call?

Having a bit of trouble figuring out how to obtain the desired value within this function. Any ideas? Thanks! temp = exotics[i].split(','); if ($.inArray(temp[0], tblProbables) != -1) { item = $("<li><a id='" + temp[0] + "&apo ...

Angular component.html does not compile due to a check that includes inline array creation

There is an enum called Status: export enum Status { SOME_VAL = "SOME_VAL", SOME_VAL_2 = "SOME_VAL_2", SOME_VAL_3 = "SOME_VAL_3"; } Also, I have an interface named SomeInterface: export SomeInterface { status? ...

How to add a subtle entrance animation to text (demonstration provided)

Apologies for the brevity, but I could really use some assistance with replicating an effect showcased on this particular website: My understanding is that a "fadeIn" can be achieved using jQuery, however, I am at a loss as to how to implement the 3D effe ...

What is the best method to add markup for an ASP button into an ASP page that is stored in a text file?

Is there a way to include ASP markup from a text file on the page? I am integrating the Azure Maps service into our project and need to have an ASP button within a popup displayed on pins. However, I am struggling to achieve this. We currently have a "te ...

retrieve essential data from Firebase using JavaScript

Currently, I am utilizing the get() method to retrieve data in my React Native application. Here is the code snippet that I am using: firebase .firestore() .collection("users") .doc("test") .get() .then(response => { console.log(respo ...

The onKeyUp event in Material-UI components does not seem to be functioning as

I am experiencing an issue with a material-ui component Grid where the onKeyUp event does not seem to be triggering as expected. Here is the code snippet: <Grid item xs={12} onKeyUp={handleClickOnKeyUp} sx={{cursor: "pointer"}} onClick= {ha ...