简体   繁体   English

AngularJS $资源| 在答应解决之前不要更新视图

[英]AngularJS $resource | don't update view until promise resolved

I am wanting to use $resource to make a RESTful update on our server but the view get's updated as soon as the user clicks when I would like it to not update until the server sends a response. 我想使用$ resource在我们的服务器上进行RESTful更新,但是一旦用户单击,视图更新将立即更新,而我希望它在服务器发送响应之前不更新。 I am using a controller with a service layer that uses a rest resource. 我正在将控制器与使用其余资源的服务层一起使用。

Template: 模板:

<tbody>
    <tr ng-repeat="user in users">      
        <td><button class="radius tiny button" 
                ng-click="toggleUserActive(user)" 
                ng-bind="user.active ? 'Disable User' : 'Enable User'">
            </button>
        </td>
    <tr>
</tbody>

Controller: 控制器:

angular.module('admin', ['admin.AdminService'])

  .controller('adminCtrl', function ($scope, adminService) {

    $scope.toggleUserActive = function(user){
      adminService.toggleUserDisabled(user).then(function(response){
        // Want the update to happen here
        user.active = response;
      });
    };

  });

Service: 服务:

angular.module('admin.AdminService', ['rest'])

  .service('adminService', function AdminService(UserRest){

    this.toggleUserDisabled = function(user) {
      user.active = !user.active;
      return UserRest.update(user).$promise.then(function(result){
        return result.active;
      });
    };

  });

Rest service: 休息服务:

angular.module('rest', ['config','ngResource'])

  .factory('RestEndpoint', function (apiEndpoint) {
    return {
      users: apiEndpoint + '/admin/users/:username'
    };
  })

  .factory('UserRest', function ($resource, RestEndpoint){
    return $resource(RestEndpoint.users, {username:'@username'},{
      update: {
        method: 'PUT'
      }
    });
  });

How can I code this where the view does not update until response has made it back? 我如何编写代码,以使视图在响应返回之前不会更新?

You could use something like this in your view 您可以在视图中使用类似的内容

ng-show="user.active"

which will show once the $scope is updated with that new data. 当$ scope用该新数据更新后,它将显示。

I have not used the rest service as you are at the moment, but doing something similar with API calls, I used the $q and promises. 目前我还没有使用rest服务,但是在API调用上做了类似的事情,我使用了$ q和promises。 Can you use the $q and promises in the controller, so the controller codes does not continue until the responses are received? 您可以在控制器中使用$ q和Promise,以便控制器代码在收到响应之前不会继续吗?

.controller('MyController', function($scope, $http, $q) {
    var JSON1 = $http.get('example1.json');
    var JSON2 = $http.get('example2.json');

    $q.all([JSON1, JSON2]).then(function(results) {
        ...
    });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM