$scope.apply is triggering both "catch" and "then" handlers

I am trying to ensure that the content of a page in Angular 1.6.2 and UI router is only displayed once it has been confirmed on the server that the user has the appropriate role/permissions.

It seems like without using $scope.apply(), the catch() function does not get triggered, but for some reason this issue is resolved when I include it. Without $scope.apply(), the vm.showContent variable does not update the view as expected.

I have checked for any Angular or JS errors and found none, so I believe the problem lies specifically with the code provided.

View/HTML

<div ng-show="data.showContent">
 // my html, not to be shown until vm.showContent is true     
</div>

Controller

// more JS
var vm = this;
vm.showContent = false;
// more JS
vm.hasRole = function (role, toState, event) {

    Auth.hasRole(role).then(function (data) {
        vm.showContent = true;
        // $scope.apply() is necessary for updating the view
        $scope.apply();
        alert('has role'); // success message
    }).catch(function () {
        alert('does not have role') // error message even if $scope.apply() is added
        if (event != false) {
            event.preventDefault();
            $state.go('no-permission');
        }
    });
}

Answer №1

Take a closer look at the value returned in the error response:

//}).catch(function () {
//LOG error response
}).catch(function(errorResponse) {
    console.warn(errorResponse);
    alert('does not have role') // also triggers even with $scope.apply();
    if (event != false) {
        event.preventDefault();
        $state.go('no-permission');
    }
});

The use of $scope.apply() is likely causing an issue:

Error: $rootScope:inprog Action Already In Progress

If an error occurs within a success handler in a promise chain, the $q service will move to the first rejection handler in the sequence.

For additional details on this error, refer to AngularJS Error Reference - $rootScope/inprog


Changes in AngularJS 1.6 regarding thrown errors in promises

Prior to version 1.6, thrown errors in success and rejection handlers would result in console error messages. AngularJS 1.6 now treats thrown errors the same as regular rejections:

$q:

With the implementation of e13eea, an error thrown from a promise's onFulfilled or onRejection handlers is handled identically to a standard rejection. Previously, these errors were also passed to the $exceptionHandler() while still rejecting the promise due to the error encountered.

--AngularJS Developer Guide - Migrating from v1.5 to v1.6 - $q

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

Save canvas as an image, with the option to incorporate additional text from a textarea element on the page into

I am currently working with a canvas element using Fabric.JS. Beneath the canvas on the screen, there is a textarea within the DOM. The download button on the page successfully downloads the canvas element as an image. However, I now need to include the t ...

What is the best way to display multiple values in a single column in a datatable?

This function works effectively in rendering the code: { "data": "assignedTo", "render": function (data) { var btnDetail = "<a href='/Ticket/TicketDetail?ticketI ...

What is the method to display a group label using ng-table?

Does anyone have experience creating a group in ng-table? <div> <div ng-controller="ContractsController" style="position: relative;background:whitesmoke; border:1px solid lightgray; border-radius:5px; margin-top:0px; margin-bottom:5px; h ...

designing the structure of directories and routes for express and angular applications

I'm new to using express and angular. After browsing through some answers in the forum, I stumbled upon the express angular seed project. My main question involves the directory structure and routing used in this seed project. In the angular seed ...

How can I efficiently distribute a function that is linked to my scope across multiple controllers?

I have implemented a function that I am attaching to my scope like this. This function is crucial for my HTML pages, so I am using it in multiple controllers. Since all my controllers are top-level controllers, I cannot place this function in a higher-up c ...

Why does my value always revert to 0 whenever I switch screens while utilizing async storage?

Utilizing a stack Navigator, my primary screen is tracker.js, and the secondary one is macros.js. In macros.js, I have the ability to manually input nutritional macros (calories, Fats, Carbs, Protein) and add them to my UsedDailyCalories. However, when I ...

The sorting feature is not performing as anticipated

I'm dealing with an array of objects fetched from the backend. When mapping and sorting the data in ascending and descending order upon clicking a button, I encountered some issues with the onSort function. The problem lies in the handling of uppercas ...

Having trouble with Passport.js authentication not functioning properly

Setting up passport for the first time and opting for a single Google sign-in option. I've gone through the process of registering with Google APIs to get everything set up. However, when my app calls '/auth/google/', it fails without any re ...

Dealing with AngularJS: Issue arises when attempting to inject $modal into a controller nested within a directive

Our team has implemented a custom directive that wraps around a checkbox and utilizes transclusion to inject content into it. Here is an example of the setup: somecheckbox.js angular.module('namespace.directives') .directive('someCheckbox& ...

The fusion of game loop and digest cycles by Angular services

I have successfully integrated my custom 2D JavaScript game engine with Angular. This game revolves around the space theme, where the engine takes care of simulating the space environment while Angular manages the trading menus with space stations and othe ...

What is the best way to trigger a localstorage change event using Vue.js?

I'm currently facing an issue with my Vue app related to updating user information stored in localStorage. I've implemented a solution using websockets in App.vue within the mounted function, as shown below: window.Echo.channel("user." ...

The clash between two jQuery plugins featuring identical function names

I have encountered a dilemma while working on a large website that includes two conflicting jQuery plugins for autocomplete functionality. The first plugin is jquery.autocomplete.js (not part of jQuery UI) which defines the autocomplete function like this ...

Having difficulty accessing `props` in a React JS and Next JS application

Currently, I am developing a React application that utilizes Server Side Rendering. In this project, I am using React Js and Next Js as my primary framework. My goal is to retrieve initial props using the getServerSideProps method by consulting the documen ...

IE8 encountering issues with Jquery ajax() request

My current issue involves submitting data using ajax from forms with a class of ajax. This functionality works flawlessly in Firefox, Safari, and Chrome, but is unsuccessful in Internet Explorer. ajax: function() { $('form.ajax').live(&apo ...

What causes errors in my AJAX request based on the particular file extension?

Utilizing JavaScript and jQuery, I have a function that loads data using $.get(url, function(response){ /* ... */});. The data is retrieved from a text file and handled within the response function of the JavaScript. Recently, I encountered an issue on my ...

What is the reason behind fullstack-angular generator utilizing Lo-Dash's merge rather than document.set?

This is the original code snippet used for updating: exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } Thing.findById(req.params.id, function (err, thing) { if (err) { return handleError(res, err); } if(!thing) { ...

Encountering an unexpected end of input error while making an API call using the fetch()

I'm looking to transition an API call from PHP to Javascript for learning purposes. Unfortunately, I can't make any changes on the API side as it's an external source. When attempting to use fetch() due to cross-origin restrictions, my scrip ...

displaying li tag depending on the index value within angularjs

I have an HTML structure similar to the following: <div class="main"> <ul> <li ng-repeat='save in saves'> <h3>{{save.name}}</h3> <div > <ul> ...

In Angular version 1.5, the default response status for errors is consistently set to -1

Having trouble with API calls? Let me explain the setup first. The entire frontend application is based on AngularJS 1.5 and hosted on various domains such as app1.mydomain.com, app2.mydomain.com, appN.mydomain.com The API (built on Symfony2 - FOS Rest) ...

AngularJS Reload Scenario: A new way to refresh and enhance

My current project involves the development of a mobile app where I am retrieving data from a REST GET call. Everything is running smoothly. However, I would greatly appreciate expert advice on how to seamlessly re-render this data if the user decides to ...