Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 308
dev.meghraj Avatar asked Oct 20 '22 04:10

dev.meghraj


1 Answers

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

enter image description here

like image 81
Jossef Harush Kadouri Avatar answered Oct 23 '22 08:10

Jossef Harush Kadouri