Reached the maximum number of iterations for Angular 10 $digest() function

Currently, I am following a MEAN stack tutorial on Thinkster and encountering an issue with my Angular factory service.

Angular.js:11598 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: []

Here is a snippet from my app.js file:

app.factory('posts', ['$http', function($http){
    var o = {
        posts: []
    };
    o.getAll = function() {
        return $http.get('/posts').success(function(data){
            console.log(data)
            angular.copy(data, o.posts);
        });
    };
    return o;
}]);

I also have route provider configurations in my config file:

$stateProvider
    .state('home', {
        url: '/home',
        templateUrl: '/home.html',
        controller: 'MainCtrl',
        resolve: {
            post: ['$stateParams', 'posts', function($stateParams, posts) {
                return posts.get($stateParams.id);
            }]
        }

    })

I am unsure what the issue might be...

Any assistance would be greatly appreciated. Thank you in advance!

Answer №1

.success has been deprecated, so I will be using then instead.

It seems like this is the message you intended to convey.

app.factory('posts', ['$http', function($http){
    var o = {}; 
    o.get = function(id){
        return $http.get('/posts/'+id).then(function(response){
            return response.data;
        });
    }
    o.getAll = function() {
        return $http.get('/posts').then(function(response){
           return response.data;
        });
    };
    return o;
}]);


 resolve: {
        post: ['$stateParams', 'posts', function($stateParams, posts) {
            return posts.get($stateParams.id);
        }]
    }

// usage of the factory in controller : 
    posts.getAll().then(function(posts){
         $scope.allPosts = posts;
    })
    posts.get(id).then(function(post){
        $scope.post = post;
    })

Here are some key points:

  1. then/ success are chainable; remember to use the return statement to ensure that the next chain gets the data it needs.
  2. It's unclear where you got your
    return posts.get($stateParams.id);
    line from, so I made a relevant addition for clarity.

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

directive ng-click not responding

drawer-card.html (template) <div class="drawer-card-wrapper"> <div class="drawer-card-icon" ngClick="dcCtrl.toggle()"> <i class="icon--{{ icon }}"/> </div> <div class="{{'drawer-card ' + (classesToAdd || '&apo ...

Unleash the power of jQuery to leverage two different input methods

Here is the code I'm working with: $('input[type="text"]').each(function(indx){ Right now, this code targets input elements with type "text". But how can I modify it to target both inputs with type "text" and "password"? Any suggestions o ...

Tips on using the ref attribute in Vue.js to focus on an input element

In my Vue.js component for 2FA, I have implemented the following structure: <template> <div :class="onwhite ? 'on-white' : ''"> <input :id="`n1`" ref="n1" v-model=&quo ...

Serious issue: a dependency request is an expression (Warning from Angular CLI)

I am currently exploring the dynamic loading of lazy child routes within a lazy routing module. For example: const serverResponse = [ { path: "transaction", children: [ { path: "finance", modulePath: &qu ...

Concealing the rear navigation button within the material carousel

I have a material css carousel, and I am trying to hide the back button on the first slide. I attempted to use the code below from a previous post The following code snippet prevents the user from looping through the carousel indefinitely. Stop looping i ...

Executing Selenium WebDriver to interact with a hidden element

Hello, I am interested in learning how to interact with hidden elements and disable them using Selenium WebDriver. I've managed to achieve this with Selenium 1 by using the following code: selenium.click(id="idOfHiddenField"); Unfortunately, this a ...

Load a JSON file into the app.js of your project

Could someone please help me figure out how to successfully load a JSON file into my project's app.js? I've tried using the following code snippet: var j = require('./JSON1'); However, it didn't work as expected. My goal is to la ...

Top strategies for avoiding element tampering

What is the best solution for handling element manipulation, such as on Chrome? I have a button that can be hidden or disabled. By using Chrome's elements, it is possible to change it from hidden/disabled to visible/enabled, triggering my click functi ...

The MVC execution sequence: Controller initialization happening after Ajax call

I'm struggling to understand the execution order in MVC architecture. In my code, I am overriding initialization in the following way: public class HomeController: Controller { protected override void Initialize(RequestContext requestContext) ...

What is the best way to check the difference between the current date and time with another date and

Seeking assistance in comparing 2 dates using JavaScript has been a bit challenging for me. I haven't found the exact solution on this platform yet. As a beginner in JavaScript, I initially assumed that obtaining the current date and time would be a s ...

The new pop-up window appears smaller than expected in Internet Explorer

There has been a bug report regarding the course opening in a smaller popup window. The JavaScript code used to open the popup is: course_window=window.open(urlString,"", "toolbar=0,directories=0,location=0,status=0, menubar=0,fullscreen=0,scroll ...

Float over a specific line in a drawing

I am looking to develop a unique rating system using css, html, and potentially js : https://i.sstatic.net/pQP79.png My goal is for the user to hover over a specific section of a circular stroke and have it fill with a particular color, all while maintai ...

Enhancing the templateUrl with additional value in AngularJS and PHP

I am having trouble capturing the value of the {fold} and adding it to the templateUrl. The php file show.person.php is returning an error because it is only recognizing 'id' as '{fold}' and not as a number like '54' In my co ...

Is the array empty once the functions have been executed?

app.post('/api/edit-profile', regularFunctions, async function (req, res) { let email = req.body.email let password_current = req.body.password_current connection.query('SELECT * FROM accounts WHERE id = ?', req.body.id, asy ...

Utilizing JavaScript to retrieve data from a JSON-parsed SOAP envelope

Welcome to the exciting world of development! This is my first post, so please bear with me if I ask a seemingly silly question. Currently, I am utilizing Xml2js for sending a SOAP request and then converting the response into JSON format. However, I&apos ...

Is relying on getState in Redux considered clunky or ineffective?

Imagine a scenario where the global store contains numerous entities. Oranges Markets Sodas If you want to create a function called getOrangeSodaPrice, there are multiple ways to achieve this: Using parameters function getOrangeSodaPrice(oranges, s ...

Preserving variable scope in JavaScript even after defining a function

I am facing an issue with my JavaScript code that involves invoking a function within a function: var obj = { // returns the function with prevent default prepended. run: function(functor, context){ return function(e){ e.preventDefault(); ...

Automatic logoff will occur after 15 minutes of inactivity in C# programming language

After a period of 15 minutes, the following method logs out the user. However, it currently logs out the user even if they are active. I am seeking a solution where the method will only log out the user if they have been inactive for the full 15 minutes. ...

Pressing a key once causing two actions when managing content in a separate window

Issue: I am facing a problem where I receive double keypresses from one key event when the event updates content in two separate windows. (Please keep in mind that I am not an expert in this field and appreciate your understanding.) I am attempting to use ...

Is it possible to dynamically add an id or class to an element using document.createElement in JavaScript?

As a beginner in the world of JavaScript, I understand that the code structure I have used here may not be ideal for real-world applications. However, I am using it to practice my understanding of for loops and fetching JSON data. My main query is whether ...