What is the best way to refresh my view model while using chained promises?

I've recently started learning about promises and I'm facing a challenge with updating an object in my view from two chained promises:

function Test($resource, FC, UserDetailsService) {
    'ngInject';

    var self = this;

    self.data = {

    };

    function getTestData() {
        firstPromise.then(function(response) {

            //I want self.data to be displayed in my view
            angular.extend(self.data, response);
            //Now my view should display my object

            resource().get(user)
                .$promise.then(function(responsePts){
                    //And THEN update/refresh my view here
                    angular.extend(self.data, responsePts);

            });
        });
    };

    self.getTestData = getTestData;

};

EDIT: firstPromise is exposed in another service and used by other services:

$resource(apiUrl).get(user).$promise.then(function(bookData){
    angular.extend(self.bookings, bookData);
});

In my controller:

function TestController(Test) {
    'ngInject';

    var $ctrl = this;

    $ctrl.testData = {};

    Test.getTestData();
    $ctrl.testData = Test.data;

};

Instead of self.data being displayed only after the resolution of the second promise, how can I make my object available for my controller directly when the first promise is resolved?

Answer №1

When dealing with a promise from the $q Service, if the view is not updating as expected, you can use $q.when() to convert the unknown promise into a $q Service promise:

function getTestData() {
    //firstPromise.then(function(response) {
    $q.when(firstPromise).then(function(response) {

        //Showing self.data in the view
        angular.extend(self.data, response);
        
        //Updating the view
        return resource().get(user).$promise;
    }).then(function(responsePts){
        //Update/refresh the view here
        angular.extend(self.data, responsePts);

    });
};

The $q Service promises work seamlessly with the AngularJS framework and its digest cycle.

$q.when(value)

This function wraps an object that could be either a value or a promise into a $q promise. It is useful when you are unsure whether an object is a promise or not, or if the promise originates from an untrusted source.

-- AngularJS $q Service API Reference - $q.when

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

Trouble with jQuery: Tackling a Basic String and Variable Issue

I'm having trouble incorporating my variable into this specific string: var liPad = 20; $(this).css({'width' : width , 'height' : height, 'padding' : "'0px' + liPad + 'px'"}); The desired outcome is ...

Tips for monitoring multiple values in a Vue 3 script setup

Within my code, I currently have a watcher set up like this (inside <script setup>): const form = reactive({ body: '', image: '' }) watch(() => form.image, () => { console.log(form.image) }) I am looking to enh ...

Troubleshooting a problem with jQuery: alter background color when checkbox is

I recently created a script to change the background color when a radio button is selected. While it works for checkboxes, I noticed that when another radio button is selected, the previous one still remains with the selected color. <script type="text/ ...

Can anyone suggest a more efficient approach to handling variations using CSS?

Within the message component, there are currently only two variants available: error and success. This project is built using vue3 script setup and utilizes SCSS for styling. <script setup lang="ts"> defineOptions({ name: 'Notificat ...

Is there a way to conceal 'private' methods using JSDoc TypeScript declarations?

If we consider a scenario where there is a JavaScript class /** * @element my-element */ export class MyElement extends HTMLElement { publicMethod() {} /** @private */ privateMethod() {} } customElements.define('my-element', MyElement) ...

JavaScript Issue Causing Jquery Carousel Dysfunction

I am having trouble with the slider I created using JS Fiddle. The link to the slider is not working and I need some assistance. Click here for the slider <div class="row"> <div id="myCarousel" class="carousel slide vertical"> &l ...

Example of fetching Pubnub history using AngularJS

I am not a paid PubNub user. I am utilizing the example code for an Angular JS basic chat application from PubNub, and I want to access the chat history. This specific example can be found on the PubNub website. git clone https://github.com/stephenlb/an ...

Tips for setting NgForm value within an Observable and verifying its successful implementation

Exploring the functionality of NgForm, I am testing to validate if the value of a form gets updated when the state of the store changes. @ViewChild('form') form: NgForm; ngOnInit() { this.subscription = this.store.select('shoppingList&apos ...

What is the best way to retrieve a unique identifier from multiple arrays and store it in one shared variable?

I have an array stored locally and I need to retrieve the "name" ID from all of them. How can I achieve this using AngularJS or JavaScript? [{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85cfeaedebc5e4abe6eae8">[ ...

Is it possible for me to generate HTML using JavaScript?

Below is the javascript code I have written, saved as create.js: var stuff = document.querySelector(".stuff"); var item = document.createElement('div'); item.className = 'item'; stuff.appendChild(item); This is the corresponding HT ...

What is the best way to extract specific values from one JSON object and transfer them to another using lodash?

//I have a pair of objects var obj1={ "name":"mayur", "age":23 } var obj2={ "name":"keyur", "age":29, "limit":54, "surname":"godhani" } //I am familiar with one approach var j1 = {name: 'Varun', age: 24}; var j2 = {code: &ap ...

Ensure that selected options are unique across multiple selections

Could you help me with a question that involves matching pairs of words in both Russian and English? <div class="form-group" id="question4"> <label for="q4FirstSelectEN">4</label> <div class="row"> <div class="col-lg ...

Prevent title flickering in Android using Ionic

I am attempting to create a tab content page using the "standard" method recommended by the ionic template example. However, I have noticed that when switching between tabs on Android, the view title flickers. This issue is not present on iOS or desktop b ...

trouble with phonegap javascript ajax integration

I'm new to app development and I've been trying to create a mobile app using PhoneGap. I have a remote shared server that contains a MySQL table. My goal is to sign up a user, then send the data via JavaScript and AJAX to a PHP server page that w ...

Mastering the art of integrating a multi-step form in React

While developing a multi-step form in my React 17.0.1 application using Typescript version 4.1.2, I came across this helpful guide: https://dev.to/sametweb/how-to-create-multi-step-forms-in-react-3km4 The guide was clear up to step 6, which I decided to s ...

While iterating over each item in the List<string> retrieved from an AJAX GET request in JavaScript

Trying to iterate through a list of strings and display them on the page, but facing an error as described in the title... "Uncaught TypeError: response.forEach is not a function" I've looked into for loops in JavaScript, but they seem to work wit ...

What is the best way to extract parameters from a JSON object?

Here is the complete code: $.post('test.php', { id: id },function (data) { console.log(data); var Server = data.response.server; var Photo = data.response.photo; console.log(Server); console.log(Photo); }); When I receive data I get JSON data ...

Why are Actions and Reducers essential components in the Redux framework?

Despite my experience with Redux, I still struggle to grasp the purpose of actions and reducers. The documentation defines a reducer as (previousState, action) => newState, a concept also seen in React's useReducer. Having one function handle all ...

Utilizing Promise.all with Axios in a Node.js environment

I seem to be facing a challenge in waiting for results from multiple axios promises before proceeding with further processing. The console.log("test"); statement gets executed prematurely, before the completion of other method calls. I suspect that the way ...

Creating unit tests for an Angular controller using Jasmine

When my controller loads in Angular, I have a set of initializations that need to be performed. Some are local while others involve making http calls. While writing test cases, I currently initialize the controller in each test case to check if variables ...