Creating a request again after a promise has been fulfilled in Angular

I'm struggling to understand a simple concept here. My objective is to retrieve data from a service, which fetches data from an endpoint, and then be able to update that stored data by refreshing the endpoint.

.service('myService', function($http) {
    var self = this;    

    this.myData = {};

    this.getItem = function() {
        return $http.get('/path/to/endpoint')
            .then(function(res) {
                self.myData = res.data;  // the data structure is like: { x: 1, y: 2}
            }); 
    };
})

.controller('mainCtrl', function($scope, myService) {
    myService.getItem();
    $scope.data = myService.myData;

    window.logService = function() {
        console.log(myService);  // { getItem: function(){...}, data: {x: 1, y: 2} }
    };
});

<div ng-controller="mainCtrl">{{data.x}}</div> <!-- Doesn't reflect the updated data from the promise -->

This situation seems puzzling. Even after calling window.logService() once the promise is fulfilled and the data is in place, the view fails to update accordingly.

Answer №1

Angular continues to monitor the {} reference even when you change the value.

To ensure that the watched object is updated and your view displays the correct information, consider using angular.copy() within the callback function.

.then(function(res) {
    angular.copy( res.data, self.myData);
});

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

Saving decimal values in a React Material UI textfield with type number on change

I am currently working on a textfield feature: const [qty, setQty] = useState({ qty: "0.00" }); ..... <TextField required id="qty" type="number" label="Qtà" value={qty.qty} step="1.00& ...

Selecting an item with Material UI AutoComplete now automatically clears the value

After making a selection, I want to clear the value in the input field immediately. Currently, the value is cleared on blur but not upon selection. <Autocomplete disabled={showTextField} className="center-vertically" options={listOfDependencies ...

Overlap and cover additional elements within a DIV

I am looking to create a versatile function that can effortlessly overlay various elements such as selects, textfields, inputs, divs, tables, and more with a partially transparent div matching their exact height and width. I have managed to obtain the pos ...

Creating a canvas with multiple label introductions can be achieved by following these

I am looking to group labels and sublabels on the x-axis of a canvas component. Currently, I only have sublabels like: RTI_0, RTI_1... I would like to add labels to these sublabels like: RTI = {RTI_0,RTI_1,RTI_2] BB = {BB_0, BB_1,BB_2,BB_3] <div cla ...

"The Material UI date picker is encountering an issue with the error prop, which is being evaluated

I have developed a date picker that utilizes the Jalali calendar. While attempting to pass error checking using the error prop in the following code: <LocalizationProvider dateAdapter={AdapterJalali}> <MobileDatePicker label={lab ...

The art of bringing a pseudo class to life through animation

Seeking assistance with achieving a unique effect on click event. I have set up a slanted or razor-blade style div using a parent div element and a pseudo-element :after (as shown below). My goal is to change the skew angle when the user clicks on the pare ...

What is the method for retrieving the IDs of checkboxes that have been selected?

I attempted running the following code snippet: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://static.jstree.com/v.1. ...

Update the image on a webpage within a template using AJAX code

I manage a website that utilizes templates. Within the template, there is a main image that I need to replace on specific pages, not throughout the entire site. I am seeking a way to change this main image to a new one on select pages using Ajax. Upon re ...

When using JSON stringify, double quotes are automatically added around any float type data

When passing a float data from my controller to a JavaScript function using JSON, I encountered an issue with quotes appearing around the figure in the output. Here is the JS function: function fetchbal(){ $.ajax({ url: "/count/ew", dataType: "jso ...

Creating responsive tabs that transition into a drop-down menu for mobile devices is a useful feature for

I am looking to create a responsive tab design that drops down like the example shown below: Desktop/Large Screen View https://i.stack.imgur.com/hiCYz.png Mobile View https://i.stack.imgur.com/gRxLv.png I have written some code for this, but I am unsure ...

Ways to adjust the height of one panel based on the height of surrounding panels

I have a layout with three panels: two on the left side and one on the right. <div class="row"> <div class="col s6"> <div class="panel"> content1 </div> <div class="panel"> ...

Discover the Magic of CSS Animation

I am not experienced in CSS animations and have limited knowledge about animations. I am trying to create an animation where a grey box slides down from the top line above the login/register section, but currently it only fades in. If anyone can provide an ...

Click on a Marker to automatically zoom to its location using Leaflet mapping technology

I have successfully implemented a feature to display markers on the map from a geojson file. Currently, when I hover over a marker, I can see its properties in a popup. However, I now want to enhance this functionality so that when a user clicks on a mar ...

What is the best way to organize an array both alphabetically and by the length of its elements?

Imagine I am working with an array like this: ['a', 'c', 'bb', 'aaa', 'bbb', 'aa']. My goal is to sort it in the following order: aaa, aa, a, bbb, bb, c. this.array= this.array.sort((n1, n2) => ...

A guide on immediately invoking a method when a class is initialized in JavaScript

I'm having some trouble with a class I created to handle user information. When I try to add an init() function to the class so that it runs as soon as the class is initialized, I keep getting a SyntaxError. I've tried following the advice from ...

Learn how to transform the html:options collection into html:optionsCollection

What is the best method to transform this code snippet: <html:options collection='catList' property='catId' labelProperty='catName'> using the <html:optionsCollection> tag? ...

Load the iframe element only when the specified class becomes visible within the container div, without relying on jQuery

I am facing a unique challenge where the performance of my page is significantly impacted by loading multiple iframes. These iframes are contained within popup modals, and I would like to delay their loading until a user clicks on the modal. When the mod ...

Exploring the capabilities of Serenity/Js for conducting tests with the protractor-Jasmine framework. Are there any specific features in Serenity that cater to

I am in the process of integrating serenity reports into my tests built using the protractor-jasmine framework. So far, all my research has only shown examples of serenity integration with the protractor-cucumber framework. Below is a sample config file ...

Dealing with code issues in Subscription forms using AJAX and JQuery

Currently, I am independently studying jQuery and grappling with the Mailchimp Opt-In form code. Despite various existing queries on this topic, I am curious about why my own implementation, as a beginner in jQuery, is not functioning correctly. My intenti ...

What is the importance of $scope.apply in relation to Angular's $q?

Currently, I am experimenting with AngularJS's implementation of Promises using $q as guided by their official documentation. I decided to test out the code snippet provided on https://docs.angularjs.org/api/ng/service/$q // In this example scenario, ...