如何从模块实例获取服务实例[Angular]

时间:2014-08-02 08:44:13

标签: javascript node.js angularjs angular-services

我已经定义了一些模块,并且使用该模块也提供了服务,如下所示

var services=angular.module('app.services', []);
services.factory('ApiService', function($http,$cookies,UserService){

        var dataFactory = {};

        dataFactory.request=function(url,data,next){
            return "Hi";
        };

        return dataFactory;

});

现在在另一个脚本中,我可以访问模块,如

services=angular.module('app.services')

但是如何从该模块中获取服务实例,如

apiService=angular.module('app.services').service('ApiService')

1 个答案:

答案 0 :(得分:3)

编辑:

在阅读并理解了作者的评论之后,如果不允许用户,他实际上是想阻止整个应用程序。他希望通过重用他ApiService工厂中编写的相同代码来实现这一目标。

-

您可以“挂钩”在控制器之前调用的app.run函数,您可以利用$window.location.href将用户重定位到其他页面或网站(如果不允许)

我已使用app.run条目更新此 plunker

<强> app.js

var app = angular.module('app', ['app.services']);

app.run(function(ApiService, $window) {
  result = ApiService.request();

  // This is where you check your permissions
  var has_permissions = false;
  // ...

  if (!has_permissions) {
    alert('being transferred to plnkr.co due to lack of permissions');
    $window.location.href = 'http://plnkr.co/';
  }

  // Otherwise, continue normally

});

原件:

我做了 plunker

如果您将所有逻辑分离到api.services模块,请将其包含在您的应用中

<强> app.js

var app = angular.module('app', ['app.services']);

然后您可以通过引用所需的工厂 - ApiService

来使用它
app.controller('myCtrl', ['$scope', 'ApiService',
  function($scope, ApiService) {

    $scope.result = ApiService.request();

  }
]);

<强> app.services.js

var services = angular.module('app.services', []);


services.factory('UserService', function() {

  var UserService = {};

  UserService.foo = function() {
    return "foo";
  };

  return UserService;

});


services.factory('ApiService', function($http, UserService) {

  var ApiService = {};

  ApiService.request = function(url, data, next) {
    return UserService.foo() + " Hi";
  };

  return ApiService;

});

<强> plunker

enter image description here

相关问题