Is it possible to inject one service into another service in angularJS?
Yes. follow the regular injection rule in angularjs.
app.service('service1', function(){});
//Inject service1 into service2
app.service('service2',function(service1){});
Thanks to #simon. It is better to use Array injection to avoid minifying problem.
app.service('service2',['service1', function(service1) {}]);
Yes. Like this (this is a provider, but same thing applies)
module.provider('SomeService', function () {
this.$get = ['$q','$db','$rootScope', '$timeout',
function($q,$db,$rootScope, $timeout) {
return reval;
}
});
In this example, $db is a service declared elsewhere in the app and
injected into the provider's $get function.
In order to avoid any confusion, I think it is also worth mentioning that if you are using any other services (e.g. $http, $cookies, $state) in your childService, then you also need to explicitly declare them.
e.g.
function() {
var childService = function($http, $cookies, parentService) {
// Methods inherited
this.method1Inherited = parentService.method1();
this.method2Inherited = parentService.method2();
// You can always add more functionality to your child service
angular.module("app").service("childService", ["$http", "$cookies", "parentService", childService]);
}());
You can either declare the services you are using inside your child in an array and then they get injected automatically, or inject them separately with the $inject annotation:
childService.$inject = ["$http", "$cookies", "parentService"];
angular.module("app").service("childService ", childService );
Related
i'm very much new to angular and trying to access localStorage. Here is the code. Please help me figure that out if it is not the right way to define and use. Thank you.
var app = angular.module("toggleApp", ['LocalStorageModule']).config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('test')
.setStorageType('localStorage');
});
app.controller("toggleController", function ($scope, $timeout,
timerParsingService, localStorageService) {
localStorageService.set('user' ,'yash');
you dont require to define any module or inject any other module in the application.
inject $window in your application and then you can access the localstorage module like this
angular.module('toggleApp', [])
.controller('toggleController', ['$scope', '$window', function ($scope, $window) {
$window.localStorage.setItem('ls', 'test');
}]);
and save the value like this
$window.localStorage.setItem('ls', 'test');
and you can retrieve the localStorage value like this
$window.localStorage.getItem('ls');
you could use ng-storge module and use
$localStorage.key = value or you could also use the getter and setter
$localStorageProvider.set('key', { k: 'value' });
I'm using ionic1 and I have multiple controller each one is for different page.
Consider the following injections:
.controller('login', function($scope, $http, $location, $state,$rootScope , auth,$timeout)
.controller('Home', function($scope, $rootScope, $http, $state,$location, $ionicNavBarDelegate, $timeout, auth, getData)
So on I have about 10 of them.
Most of the injections are common to all the controllers such as $scope,$rootScope and few others.
So I want to know if there is a one liner to inject all the dependencies in one go.
You could create a factory which returns some of the most used dependencies.
Something like this:
angular
.module('app')
.factory('common', common);
common.$inject = ['$rootScope', '$http', '$state'];
function common($rootScope, $http, $state) {
var service = {
$rootScope: $rootScope,
$http: $http,
$state: $state
};
return service;
}
then you just need to include the common service in your controller and use it like this: common.$rootScope.
Hope this helps :)
Edit
As #estus said in the comments, with $scope it would fail because $scope is a local dependency and not available in services/factories. This should not be an issue since I would recommend to avoid $scope as far as possible (use controllerAs syntax)
Injecting all dependencies contradicts the concept of dependency injection (besides the fact that controllers can have local dependencies). A dependency is what a controller depends on.
If there are several controllers that have matching dependencies, they can inherit base controller. If child controllers should have their own dependencies, this can be done with base class that automatically assigns dependencies to controller instance. Controller inheritance works best with ES6 classes:
class BaseController {
static get $inject() {
return ['$rootScope', '$scope', '$timeout'];
}
constructor(...deps) {
this.constructor.$inject.forEach((depName, i) => {
this[depName] = deps[i];
});
}
}
class SomeController extends BaseController {
static get $inject() {
return [...super.$inject, 'some'];
}
constructor(...deps) {
super(...deps);
...
}
}
app.controller('SomeController', SomeController);
I am using a service to get data from the server using $http.get() method. I am calling the function in the service and then accessing its variable from the controller. But it is not working this way.
The code is below
'use strict';
var mission_vision_mod = angular.module('myApp.mission_vision', ['ngRoute']);
mission_vision_mod.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/mission_vision', {
templateUrl: 'partials/mission_vision/mission_vision.html',
controller: 'mission_visionCtrl'
});
}]);
mission_vision_mod.controller('mission_visionCtrl', ['$scope','getMissionData','$http', function($scope, $http, getMissionData) {
$scope.visiontext = "Here is the content of vision";
getMissionData.getmissiondata();
$scope.missions = getMissionData.missiondata;
$scope.len = $scope.missions.length;
}]);
mission_vision_mod.service('getMissionData', ['$rootScope','$http', function($rootScope, $http){
var missiondata;
function getmissiondata(){
$http.get('m_id.json').success(function(data){
missiondata = data;
});
}
}]);
When i write the$http.get() function in the controller itself, it works. I am new to angular JS.
Try writing your service like this
mission_vision_mod.service('getMissionData', ['$rootScope','$http', function($rootScope, $http){
this.getMissionData=function(){
return $http.get('m_id.json');
}
}]);
Use Service in controller like this:
mission_vision_mod.controller('mission_visionCtrl', ['$scope','getMissionData','$http', function($scope,getMissionData,$http) {
$scope.visiontext = "Here is the content of vision";
getMissionData.getMissionData().success(function(response){
$scope.missions=response;
$scope.len = $scope.missions.length;
}).error(function(errorl){
//handle error here
});
}]);
Also I suggest using a better name for service -'MissionDataService' :)
EDIT- Your sequence of injected service should match sequence of injectable names specified in the array..See my last edit
['$scope','getMissionData','$http',
function($scope, $http, getMissionData
The service names don't match with the variable names.
My advice: stop using this array notation. It clutters the code and is a frequent source of bugs. Use ng-annotate.
That said, your service is not correctly defined. It doesn't have any member function that would allow it to be called. Re-read the documentation of services. Defining services using factory() is easier than defining them using service(), BTW. And the service should return the promise returned by $http. Trying to access the value returned by an asynchronous call right after making the asynchronous call will never work. Read http://blog.ninja-squad.com/2015/05/28/angularjs-promises/
Try:
mission_vision_mod.service('getMissionData', ['$rootScope','$http', function($rootScope, $http){
var missiondata;
function getmissiondata(){
$http.get('m_id.json').success(function(data){
missiondata = data;
return missiondata;
});
}
}]);
I used dependency injections in my controllers as follows.
.controller('deals_list', function ($scope, global, config, services, dealService, pagination) {
Now the app was growed. Dependencies are growing too. I want limit these injections. So is there a way to limit those with global injections or something?
What kind of procedure actually should I follow?
var myApp= angular.module('myApp', []);
myApp.run(function ($rootScope, $location, $http, $timeout, YourService) {
$rootScope.MyService = YourService;
}
Used it into controller :
myApp.controller('YouCtrl', ['$scope', function ($scope) {
// scope inherits from root scope
$scope.MyService.doSomething();
}]);
What i believe you can do is to create a service that contains all the services that you want to use. The global service is like a facade into your real service.
The option then are to create on global service with all dependencies included. Or multiple facade service which group these services
app.service("Configurations",function(global,config) {
this.global=global;
this.standard=config;
});
app.service("AppServices",function(services, dealService, pagination) {
this.services=services;
// other assigments
});
Now you can inject Configurations and AppServices
This at least gives some visibility into what your controllers are dependent upon.
I'm new to angular and have the following code.
angular.module('MyApp')
.controller('loginController', ['$scope', '$http', 'conditionalDependency',
function ($scope, $http, conditionalDependency{
}
I would like to have conditionalDependency loaded conditionally. Something like this
if(true)
{
//add conditionalDependency
}
How can this be done. I've seen this post . However, my requirement is that I have the dependency specified in function
Thanks in advance.
Not quite clear as to why you would have to have it in a named function like in your example but...
If you need conditional dependencies, I would suggest taking a look at the following:
Conditional injection of a service in AngularJS
I've used this method in a couple niche scenarios and it works quite well.
EXAMPLE:
angular.module('myApp').controller('loginController',
['$injector', '$scope', '$http',
function($injector, $scope, $http) {
var service;
if (something) {
service = $injector.get('myService');
}
});
You can use it even without injecting injector in your controller
if(something){
var injector = angular.element(document).injector();
var myService = injector.get('myService')
}
Use:
angular.injector().get('conditionalDep');
You can inject $injector once to your file and call $injector.get('dep');