$ http.get后UI未更新

时间:2015-08-02 11:35:19

标签: javascript angularjs angularjs-directive

您好我有以下angular.js控制器。

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");
  });
}

notifications.showSuccess&amp; notifications.showError方法在scree上显示通知。使用此脚本:https://github.com/alexbeletsky/ng-notifications-bar

奇怪的是,showSuccess方法实际上有效,并在showError不起作用时显示通知,并且不显示任何内容。我调试了代码,一切看起来很好,消息被添加到消息数组中,没有收到任何错误。我还尝试调用showError而不是showSuccess来验证它不是错误而且有效。

有关调用showError时未更新用户界面的原因的任何想法吗?

1 个答案:

答案 0 :(得分:0)

我认为您的问题可能位于通知服务中,因为以下示例工作正常。

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>