【问题标题】:How should I inject a CurrentUser into a controller我应该如何将 CurrentUser 注入控制器
【发布时间】:2014-07-27 09:56:57
【问题描述】:

我对 Angular 非常陌生,并试图创建一个控制器来获取属于当前用户的所有 Snod。我已经包含了我的 CurrentUserController 以供参考,但我的问题实际上是关于 SnodController,是我注入 CurrentUser 并正确嵌套调用的方式,因为虽然它可以工作,但在我看来是错误的。

抱歉,如果这是一个需要辩论和违反规则的问题,但我想知道我的方法是否朝着正确的方向前进。

var apiService = angular.module("apiService", ['ngResource']);
apiService.factory('CurrentUser', function($resource) {
    return $resource(   "http://snodbert/api/v1/users/current/",   {});
});

apiService.factory('Snod', function($resource) {
    return $resource
    (   "http://snodbert/api/v1/snods/:filter/:filterid",   {}
        ,   {   'update': { method:'PUT' }
        }
    );
});

function CurrentUserController($scope, CurrentUser) {
    var user = CurrentUser.get(function() {
            $scope.user=user;
        }
    );
}

function SnodController($scope, Snod, CurrentUser) {
    var user = CurrentUser.get(function() {
        var items = Snod.get( {filter:'owner', filterid: user.id},
        function() {
            $scope.items=items.data;
        });
    });
}

【问题讨论】:

  • 你为什么认为这是错误的?
  • 自发布以来,我不确定我是否这样做。我更面向对象而不是函数式程序员,所以嵌套调用似乎不自然。我只是想避免犯新手错误,以后不得不全部取消。

标签: angularjs angularjs-resource


【解决方案1】:

你的代码当然可以工作,但是,仅仅为了代码风格并不优雅,因为它的构建方式总是需要将回调嵌套到另一个回调中......

为了解决这个问题,你可以看看 Promises 是如何工作的,以及它们是如何在 AngularJS 中实现的:

  1. ES6 PROMISES
  2. $q
  3. Promises in ngResource

所以,看完这些页面,你应该对如何解决Pyramid of doom这个烦人的问题有了更清晰的认识。

让我们快速修改基本代码:

// old
apiService.factory('CurrentUser', function($resource) {
    return $resource(   "http://snodbert/api/v1/users/current/",   {});
});

// new
function CurrentUserServiceFactory($resource, $q) {
  var resource = $resource("http://snodbert/api/v1/users/current/", {});
  var self = this;
  
  self.get = function() {
    return resource
      .get()
      .$promise
    ;
  }
}
apiService.service('CurrentUserService', CurrentUserServiceFactory);
并且,在您的控制器中,您可以执行以下操作:

function SnodController($scope, Snod, CurrentUserService) {
  CurrentUserService
    .get()
    .then(function(userResult) {
      return Snod.get({}).$promise;
    })
    .then(function(snodResult) {
      console.log(snodResult);
    })
  ;
}

另一个很棒的事情是重新组织你的代码,试图了解你的控制器有哪些依赖项......例如,对我来说,CurrentUser 的值是一个依赖项,它应该放在 路由中-解决 (resolves are explained here)。

使用resolve你可以直接这样做:

function SnodController($scope, Snod, CurrentUser) {
  Snod
    .get({userId: CurrentUser.id})
    .$promise
    .then(function(snodResult) {
      console.log(snodResult);
    })
  ;
  
}

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多