$资源服务和控制器

时间:2014-05-05 12:14:04

标签: angularjs

我有这样的代码:

angular.module( 'APPLICATION', ['ngResource'] )

    .service( 'Service', ['$resource', function ($resource) {
      var Model = $resource( 
          '/:node/:key.json', 
          { node: '@node', key: '@key' }, 
          { 
            query: {method: 'GET', isArray: false}
          }
      );
      var responseMessage, responseData;
      var successHandler = function (resource) {
        responseMessage = { success: resource.result.message };
        responseData = resource.result.data;
      };
      var errorHandler = function (resource) {
        responseMessage = { error: resource.headers().message };
      };

      this.model = null;
      this.fetch1 = function () {
        var result = Model.query( {node: this.model.node} );
        return result;
      };

      this.fetch2 = function () {
        var result = Model.query( {node: this.model.node} );
        result.$promise.then( successHandler, errorHandler );

        return responseData;
      };
    }] )

    .controller( 'Controller', ['$scope', 'Service', function ($scope, Service) {
      Service.model = $scope.model;

      // works
      var response = Service.fetch1();
      response.$promise.then( function (response) {
        $scope.items = response.result.data;
      } );

      // doesn't work
      $scope.items = Service.fetch2();
    }] );

如何让 Service.fetch2 工作?

我想处理服务内部的数据,而不是处理器中的数据,但我无法弄清楚如何处理数据后将数据发送到控制器......

1 个答案:

答案 0 :(得分:0)

由于您的fetch2调用本质上也是异步的,因此您无法进行直接分配,因为此时结果可能无法使用。从fetch2返回一个promise。喜欢这个

this.fetch2 = function () {
        var result = Model.query( {node: this.model.node} );
        return result.$promise.then( successHandler, errorHandler );
      };

  var successHandler = function (resource) {
        responseMessage = { success: resource.result.message };
        responseData = resource.result.data;
        return responseData;
      };
      var errorHandler = function (resource) {
        responseMessage = { error: resource.headers().message };
        return responseMessage;
      };

在您的控制器中

Service.fetch2().then(function(data) {
  $scope.items=data;
});