I'm trying to change some $rootscope variables from within a controller after a I have received a promise from a service.
The $rootscope variables are used to set the html page title attribute etc.
Below is the code I have, I created a function called changeRootPageNotFound() to change the $rootscope variables. It does not work if it's called in the promise.then function.
app.controller('mainController', ['$routeParams', '$scope', '$rootScope', 'mainService', function ($routeParams, $scope, $rootScope, mainService) {
var mainCtrl = this;
mainCtrl.id = $routeParams.itemId;
var promise = mainService.getData($routeParams.id);
promise.then(function (response)
{
if (response.data.data) {
mainCtrl.data = response.data.data;
} else {
mainCtrl.data = false;
changeRootPageNotFound();
}
});
function changeRootPageNotFound() {
$rootScope.title = "Page Not Found - 404";
$rootScope.titleSuffix = "";
}
// changeRootPageNotFound(); // works here
}]);
How can I change the $rootscope variables after I have received the deferred promise from the service?
Add a
.catchmethod:The
$httpservice rejects the promise when the status is outside the range 200-299.If the
throw errorResponseis omitted, the rejection handler returns a value ofundefined. This will convert the rejected promise to a fulfilled promise that resolves asundefined. If there is no further chaining, it can be left out.A common cause of problems is programmers being unaware of this and unintentionally converting promises.
One of the subtle differences between
.catchand using the 2nd argument of the.thenmethod, is that runtime errors in the.thensuccess handler will not be caught in the rejection handler of the 2nd argument.