简体   繁体   中英

How to get service instance from module instance [Angular]

i have some module defined and services too with that module like below

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;

});

now in another script i can access module like

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

but how can i get service instance from that module like

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

Edit:

after reading and understanding the author's comments, he was actually meant to block the entire app if the user is not permitted. his desired to do it by reusing the same code written in his ApiService factory.

--

You can 'hook' to app.run function which called before your controllers and you can utilize $window.location.href to relocate user to another page or site (if not permitted)

Iv'e updated this plunker with app.run entry

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

});

Original:

i made this plunker

if you separate all logic to api.services module, include it in your app

app.js

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

then you could use it by referencing the desired factory - 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

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM