UI doesn't update after $ http.get
Hi I have the following angular.js controller.
function WorkSpacesController($scope, $http, notifications) {
$scope.Workspaces = [];
$scope.Query = "";
$http.get("api/Workspaces/GetAllWorkspaces/").then(function(response) {
for (var i = 0; i < response.data.length; i++) {
$scope.Workspaces.push(response.data[i]);
notifications.showSuccess("Added new Item");
}
},
function(data) {
notifications.showError("Could not load workspaces");
});
}
Method notifications.showSuccess
and notifications.showError
displays the scree notification. using script: https://github.com/alexbeletsky/ng-notifications-bar .
The weird thing is that the method showSuccess
actually works and displays a notification while it showError
doesn't work and displays nothing. I debugged the code, everything looks fine, the message is added to the message array and no error is accepted. I also tried calling showError
instead showSuccess
to make sure it is not buggy and works.
Any thoughts on why the UI isn't updating when called showError
?
source to share
I think your problem is probably somewhere inside your notification service because the following example is working correctly.
angular.module('app', []).controller('WorkspacesController', function($scope, $http, notifications, $templateCache) {
$scope.Workspaces = [];
$scope.Query = "";
//for the purposes of this example, put a url into the http cache so we can load it without an actual http request
//try a successful request
$http.get('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css').then(function(response) {
//for (var i = 0; i < response.data.length; i++) {
//$scope.Workspaces.push(response.data[i]);
notifications.showSuccess("Added new Item (for good request)");
//}
},
function(data) {
notifications.showError("Could not load workspaces (for good request)");
});
//try a failed request
$http.get('url_that_does_not_exist').then(function(response) {
//for (var i = 0; i < response.data.length; i++) {
//$scope.Workspaces.push(response.data[i]);
notifications.showSuccess("Added new Item (for bad request)");
//}
},
function(data) {
notifications.showError("Could not load workspaces (for bad request)");
});
}).service('notifications', function() {
return {
showSuccess: function(message) {
alert('Success: ' + message);
},
showError: function(message) {
alert('Error: ' + message);
}
};
})
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js@1.5.0" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="WorkspacesController as vm">
</body>
</html>
source to share