Deliver an assured result to a variable within the angular.extend() function

Can someone provide guidance on how to set myVar to a value returned from an asynchronous service method in the following example?

angular.extend(this, {
    myVar: (function() {
        getVal();
    })()
});

function getVal() {
    var d = $q.defer();
    MyFactory.Get()
        .then(function (resp) {
            d.resolve(resp.data);
        });
    return d.promise; // myVar should equal resp.data
};

I feel like I may be struggling with understanding promises/deferral, so any advice would be greatly appreciated.

Answer №1

If myVar is a variable, you have the flexibility to set it from any part of the controller. During initialization, you can assign it a default value or leave it undefined. You can also update its value after an asynchronous call succeeds.

angular.extend(vm, {
    myVar: 'fallback'
});

Alternatively:

angular.extend(vm, {
});

Then, in the controller:

getVar();
function getVar() {
    getVal().then(function(data){
        vm.myVar = data;
    });
}

function getVal() {
    var d = $q.defer();
    MyFactory.Get()
        .then(function (resp) {
            d.resolve(resp.data);
        });
    return d.promise; // myVar should equal resp.data
};

Or more succinctly:

getVal();

function getVal() {
    MyFactory.Get()
        .then(function (resp) {
            vm.myVar = resp.data;
        });
};

Changed this to vm to avoid potential conflicts with the this keyword.

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

Chaining Assignments in TypeScript

let a: { m?: string }; let b = a = {}; b.m = ''; // Property 'm' does not exist on type '{}'. let a: { m?: string } = {}; let b = a; b.m = ''; // It's OK Link to TypeScript Playground What occurs ...

TS: How can we determine the type of the returned object based on the argument property?

Assume we have the following data types type ALL = 'AA' | 'BB' | 'CC'; type AA = { a: number; }; type BB = { b: string; }; type CC = { c: boolean; }; type MyArg = { type: ALL }; I attempted to create a mapping between type n ...

The VueJS Hello world application is experiencing technical difficulties and is currently not functioning as

As a complete VueJS newbie, I've just started working on my very first app. It's supposed to be a simple Hello World application, but unfortunately, the code isn't quite behaving as expected :( HTML <!DOCTYPE html> <html lang=" ...

Issue with the close button on ngb-alert not functioning properly

As I develop my website, I have incorporated an ngb-alert component to display an alert message to users upon login. While the alert itself is functioning properly, I have encountered an issue with the close button being misaligned, and I am struggling to ...

After redirection to a new page, the Ionic-vue menu malfunctioned

I have developed a reusable header component named Header, which contains an IonMenu component for consistency across pages. The menu is associated with the IonRouterOutlet as per the documentation, but I am encountering an issue when navigating between pa ...

Interactive calendar feature displaying events upon hovering over a date

I need some assistance with displaying a drop-down list on full calendar events when hovering over the events. Can someone provide guidance? Here is a glimpse of what I currently have: I've attempted setting the z-index, but I can't seem to get ...

Formatting UTC time in Angular for display

After converting a group of dates to UTC in my controller, I found myself facing an unusual problem when trying to format them. When attempting to display the date in a specific time format using the code snippet below: <label>{{ '2016-07-22T1 ...

What could be the reason for the React component not re-rendering even after its prop has been updated?

One of the challenges I'm facing with an application I'm currently working on is a re-render issue. To simplify, let's say we have two components - DisplayElement1 and DisplayElement2. In this scenario, DisplayElement2 iterates through a ba ...

Error message appears when attempting to submit a form with empty values in NodeJs

I need help troubleshooting a display error that occurs when setting empty values in form fields. When I delete the row with res.redirect('/') and then attempt to register, if I refresh the page later, an error appears. However, if I keep this re ...

The synergy of Redux with scheduled tasks

In order to demonstrate the scenario, I have implemented a use-case using a </video> tag that triggers an action every ~250ms as the playhead moves. Despite not being well-versed in Flux/Redux, I am encountering some challenges: Is this method cons ...

Automated Desk: adjust page through programming

I am currently utilizing Smart Table and I would like to automatically navigate to a specific page once the controller has been created and the table is displayed. After searching on stackoverflow, I came across this code snippet that allows me to achieve ...

Is there a way to search for multiple items using just one search term?

On my app, there is a search bar that currently only looks up data for one specific attribute. For example, if I type in "Hammer," it only searches for Tool names. Now, I need to expand the search functionality to accommodate different types of strings. F ...

Updating NPM packages versions is currently restricted

I'm in the process of creating a Next.JS application using create-next-app. However, I've noticed that in the package.json file it lists the following dependencies: "eslint": "8.43.0", "eslint-config-next": &quo ...

Issues with JQuery script causing inconsistency in checking checkboxes

My code includes two functions designed to check and uncheck all checkboxes with a specific class. Initially, the functions work as expected but upon subsequent attempts to run them, the checkboxes do not function properly. Instead, the HTML code seems to ...

The AngularJS directive within a directive is failing to properly initialize the scope value

In my current setup, I am working with a controller that contains the value $scope.colorHex. As an example, I am utilizing the directive colorpickerTooltip, and within its template, I am calling another directive: <colorpicker ng-model="colorHex">&l ...

Express.js is still displaying the 'Not Found' message even after deleting the initial code

Despite multiple attempts to resolve what I initially thought was a caching issue by completely removing all code from my server, I am still facing the same problem: The default error handling provided by Express Generator in the app.js file contains the ...

Tips on adjusting the pixel dimensions of an image using a file object

Within a form on our website, users have the ability to upload an image file. To ensure quality control, I've set up validation to confirm that the uploaded file is either an image or gif format. In addition to this, I'm looking for a solution th ...

Dealing with a jQuery/Javascript/AJAX response: sending a string instead of an integer as a parameter to a

Trying to figure out how to handle passing integers as strings in JavaScript within an AJAX response. Here is the code snippet: message+="<td class='yellow' onclick='open_flag("+i+j+")'>"; The message variable is eventually inse ...

Controlling the file selection window of a browser with protractor/jasmine

The tools I am currently using are Protractor 3.3.0, Jasmine 2.4.1, and Selenium Standalone Server. My main objective is to create a test scenario where the test navigates to a specific page and then clicks on an 'upload file' button. This actio ...

reverting the effects of a javascript animation

I am expanding the size of a carousel on a specific pane by adjusting its height and position. Here is how I achieve this: if(currentPane==2) { $("#carousel").animate({height:320},1000); $("#carousel").animate({top:411},1000); $("#dropShadow") ...