如何从其他服务,AngularJS访问的承诺 [英] How to access promises from another service, AngularJS

查看:133
本文介绍了如何从其他服务,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');
})

这篇关于如何从其他服务,AngularJS访问的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆