如何从其他服务,AngularJS访问的承诺

如何从其他服务,AngularJS访问的承诺

问题描述:

我在我的服务承诺这是从另一个服务。我想要直接访问数据。

I have a promise in my service which comes from another service. I want to access the data directly.

这是我的服务(一小部分):

This is (a tiny part) of my service:

  factory('CalculationFactory', function(SizeFromPipe){
     var input = {
       sizes: function(pipe_id){
         var sizesFromPipes = SizeFromPipe.getSizes(pipe_id);
         sizesFromPipes.then(function(val){
          console.log(val); //Is an object
          return val; 
         });
     }
     return input;
  }).

这是我的的DataService

This is my "dataservice":

 factory('SizeFromPipe', function($resource, $q){
    return {
      getSizes:  function(pipe_id){
        var deffered = $q.defer();
        $resource('/api/sizes/fromPipe/:id', {'id':'@id'})
          .query({id:pipe_id},
          function(sizes){
            deffered.resolve(sizes);
          },
          function(response){
            deffered.reject(response);
          });

        return deffered.promise;
      }
    };
  })

我想从我的控制器做到这一点:

I'd like to do this from my controller:

$scope.sizes = CalculationFactory.sizes(pipe_id)

我得到了一个未定义虽然。

I get undefined though.

任何想法?

更新:添加的数据服务。我知道我可以。然后..从控制器访问此。我真的很想让我的控制器的清洁,所以如果它possbile照顾这在我的模型代替,那将是巨大的。

Update: Added the data service. I know I can access this with .then.. from controller. I'd really like to keep my controller clean so if it's possbile to take care of this in my model instead, that would be great.

我个人保持资源工厂清洁,而不是 $ routeProvider 使用决心,找到了方法来访问通过 $ route.current.scope 范围的变量。因此,分配在那里。
并在控制器中没有code,当路由改变其自动地从服务器响应。

I personally keep resource factory clean and instead using resolve in $routeProvider, and found the way to access scope variable through $route.current.scope. So, assigning right there. and no code in controller, when route changes its automatically fetch response from server.

resolve: {
  anyname: function($route, Pipe) {
    Pipe.query($route.current.params, function(data) {
      $route.current.scope.some_variable = data;
    });
  }
}

资源

something.factory("Pipe", function($resource) {
  return $resource('/api/sizes/fromPipe/:id');
})