Angular: Promise updating array but integer remains static

At the moment, I have a factory and a controller set up. The factory is responsible for updating with items retrieved from an endpoint along with the total number of pages of data. While my data array seems to be working properly, the pageCount (an integer) doesn't seem to update at all. I have double-checked to ensure that it is not returning a value of 0.

.factory('myService', function($http) {
    return {
        data: [],
        update: update,
        pageCount: 0
    };

    function update() {
        return $http.get('path/to/endpoint')
            .then(function(res) {
                angular.copy(res.data.itemsArray, this.data);
                angular.copy(res.data.pageCount, this.pageCount);
                // I also attempted this.pageCount = res.data.pageCount;
            }.bind(this));
    }
})

.controller('myCtrl', function(myService) {
    myService.update();

    $scope.data = myService.data;
    $scope.pageCount = myService.pageCount;
});

<div>{{pageCount}}</div> // This still displays the initial value
<div ng-repeat="item in data">{{item}}</div> // This section is functioning correctly

Answer №1

By implementing the update() function in the promise object, you are able to utilize the then method to manage the outcome more effectively, ensuring a more uniform result:

.factory('myService', function($http) {

    return {
        update: update
    };

    function update() {
        return $http.get('path/to/endpoint')
            .then(function(res) {
                var result = {
                    data: [],
                    update: update,
                    pageCount: 0
                };

                result.data = res.data.itemsArray;
                result.pageCount = res.data.pageCount;
                return result;
            });
    }
})

.controller('myCtrl', function(myService) {

    $scope.data = [];  

    myService.update().then(function(result) {

        $scope.data = result.data;
        $scope.pageCount = result.pageCount;
    });
});

Answer №2

When you set the primitive value from the service, the reference was lost. To avoid this issue, consider fetching the pageCount from a getter function in the service instead of directly setting it. Attempting to override the service value will result in a completely different value being stored in the scope.

This issue does not occur with arrays because they are stored as references and you made a copy of it.

factory('myService', function($http) {
    var pc = 0;
    return {
        data: [],
        update: update,
        pageCount: function() {
            return pc;
        }
    };

    function update() {
        return $http.get('path/to/endpoint')
            .then(function(res) {
                angular.copy(res.data.itemsArray, this.data);
                pc = res.data.pageCount;
            }.bind(this));
    }
})

.controller('myCtrl', 

    function(myService) {
        myService.update();

        $scope.data = myService.data;
        $scope.pageCount = myService.pageCount;
    });

    <div>{{pageCount()}}</div> // This does not update at all
    <div ng-repeat="item in data">{{item}}</div>  // This works fine

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

Ways to combine duplicate entries within a column using Ruby on Rails?

I need some help with a filtering issue related to sign names. I am trying to merge the content together if there is more than one name of the sign. You can refer to the image attached for better clarity, where I have two server names but I only want to di ...

Unable to utilize the resolved value received from a promise and returned from it

Within the code snippet below, I am retrieving a Table object from mysql/xdevapi. The getSchema() and getTable() methods return objects instead of promises. The purpose of this function is to return a fulfilled Table object that can be used synchronously i ...

AngularJS: A Step-By-Step Guide to Adding Two Values

Currently, I am utilizing the MEAN stack for my application with AngularJS as the front-end. I have two tables in which I obtained total sum values like 124.10 in the "conversion rate" column. Now, I am looking to calculate the total sum of the "conversion ...

Trouble with Next.js App Router OG Image not appearing after deployment

I am facing an issue with my Nextjs project that uses the app router. Inside the app directory, there is a file named opengraph-image.png. I have set this file to be the OG Image for the landing page, but after deploying and checking, the OG image does not ...

What limitations prevent me from using "await .getAttribute()" in Protractor, despite the fact that it does return a promise?

I have been working on transitioning my Protractor tests from using the selenium control flow to async/await. However, I am facing an issue where it is not allowing me to use await for the .getAttribute() function. Each time I try, I receive the error mess ...

Error message: "Issue occurs when sending keys to protractor element's text value and

Having trouble running this code in Protractor as I keep encountering errors, and I'm unable to retrieve the value of the anpr_box_input text. Error message: ManagedPromise::871 {[[PromiseStatus]]: "pending"} failed - should have a valid license ...

Script to pop up cancel alert box

There's a dilemma with this code - if you click CANCEL the first time the box pops up, it continues to run. I'm unsure of how to make it redirect to the underlying page when clicked on cancel for the first time. var numero= prompt ("Enter a nu ...

Error: The function `push` cannot be used on the variable `result` (TypeError)

Here is a snippet from my react component const mockFetch = () => Promise.resolve({ json: () => new Promise((resolve) => setTimeout(() => resolve({ student1: { studentName: 'student1' }, student2: { studen ...

Encountering an issue while trying to import the instanceMethods function within Sequelize

In a file, I have written a function and exported it like this: export function foo(params...) { // do something } When initializing the model, I imported the function in the following manner: import { foo } from "../path/..." instanceMethods: { foo ...

Issue encountered with websocket connection while attempting to include dependencies

My current project involves integrating charts for the graphical component using React within an Electron software. I've added interaction with buttons (sections) to insert different data into the graphs based on user clicks on one of the sections. Th ...

The overflow hidden function does not seem to be fully functional on the iPad

Struggling to prevent body scrolling when a modal pop-up appears? I've tried setting the body overflow to hidden when opening the modal and resetting it when closing, which worked fine on desktop browsers. However, mobile devices like iPod/iPhone pose ...

What is the proper way to transfer information to my ajax function from my controller?

I need to dynamically update an element on my webpage based on server-side code events. For example, when I trigger the "Start" function by clicking a button, I want the text inside a specific element to change to "Downloading", and then once the process i ...

Utilizing Google Maps API to update ImageMapType Overlay

I am utilizing the Google Maps JavaScript API to showcase weather data from a tile server. The specific tile server can be accessed here: To display the tile server, I am utilizing an ImageMapType and incorporating it into the Google Map's overlayMap ...

Configuring Vuex State

Currently, I have a prop that is being bound to a child component. My goal is to eliminate this binding and instead assign the value to a data property in a vuex global state. <VideoPip :asset="asset" v-show="pipEnabled === true" /&g ...

Troubleshooting Firebase AppCheck v8 in React: Encountering a 400 error message stating "App ID is Invalid: 'undefined'"

I've been attempting to integrate appCheck into my Firebase project. Despite following the instructions in the Firebase documentation and consulting several StackOverflow posts, I'm encountering difficulties getting it to function correctly. When ...

Display webpage content in an Iframe using Javascript after PHP code has been executed

Despite researching keywords like PHP // Javascript // Load // URL online, I'm still struggling to fully grasp the concepts. Real-life case studies have been helpful, but I must admit that I'm feeling a bit overwhelmed at the moment. I created a ...

Tips for obtaining a cropped image as form data in React after the cropping process

import React, { PureComponent } from 'react'; import ReactCrop from 'react-image-crop'; import 'react-image-crop/dist/ReactCrop.css'; class CoachDashboard extends PureComponent { state = { src: null, crop: { u ...

Demystifying Iron Ajax: Unraveling the process of parsing an array of JSON objects from a successful

When making an AJAX call to the server, I receive a response in the form of an array of objects as JSON. [{"dms":[{"serialNo":"EG0022","status":"running","firmwareStatus":"ok","latitude":37.8688,"longitude":-144.2093,"toolType":1},{"serialNo":"EG0022","st ...

Creating a worldwide entity through the use of an Immediately Invoked Function Expression

There are 2 methods I discovered for defining a global object using IIFE: (function () { var func = function () { }; window.func = func; }()); compared to: (function (myFunc) { window.func = myFunc(); }(function () { var func = functi ...

Is there a way to split the text into distinct pages within a contenteditable area, similar to the functionality in Google Docs

I've been working on developing a specialized browser-based text editor and I've encountered a puzzling question. How can I detect and split long texts into separate pages, similar to how Google Docs handles pagination? I'm aware that Google ...