how to inject factory into another factory in Angular - angularjs

I have two modules and factories in both, and I need to implement factory from the first module into another module.
angular.module('APIs', [])
.value ("myValue" , "12345")
.factory('apiUrl',['config','url',apiUrl])
function apiUrl(config,url){
}
angular.module('users.service', ['APIs'])
.factory('userService',['myValue',userService])
function userService(apiUrl,myValue){
//login function
function login(){
console.log('myValue',myValue)
console.log('loginUrl',apiUrl)
}
return {
login:login
}
}
notice: no problem when I inject myValue, but the problem in APIs Factory
and my log:
Error: [$injector:unpr] http://errors.angularjs.org/1.5.0/$injector/unpr?p0=urlProvider%20%3C-%20url%20%3C-%20apiUrl%20%3C-%20userService
at Error (native)
and sorry for my English.

I would do it like this:
If you create factory use angular.module('app').factory(). If you create service use angular.module('app').service()
Always try to have same module name. It is easier later, when you have big application, because of dependency injection.
Try to keep files separately, and concatenate it later, for example using gulp gulp-concat
Try to keep all you configuration in app.js file and, when you concatenating file, remember, this file should be on top.
I would keep values and constants in app.js file or would create new file like factory or service and include it, same as I injected it below.
app.js
(function () {
'use strict';
var app = angular.module('app', [
// other module
]);
app.value('myValue', '12345');
app.constant('myConst', 'some_constant');
app.config(['$interpolateProvider', function ($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
}]);
}());
factory.js
(function () {
'use strict';
angular
.module('app')
.factory('apiUrlFactory', apiUrlFactory);
apiUrlFactory.$inject = [];
function apiUrlFactory() {
var self = this;
self.url = 'some_url';
return self;
}
}());
service.js
(function () {
'use strict';
angular
.module('app')
.service('userService', userService);
userService.$inject = ['apiUrlFactory', 'myValue'];
function userService(apiUrlFactory, myValue) {
var self = this;
self.login = function () {
console.log('myValue', myValue);
console.log('loginUrl', apiUrlFactory.url);
};
return self;
}
}());
If you have more questions, do not hesitate to contact with me. Also try angular style guide https://github.com/johnpapa/angular-styleguide It will help you a lot.

Related

my suggestion about getter syntax in angular to handle app name duplication

I know it is a bad practice to use this syntax to register controllers in angular:
var app = angular.module('app',[]);
app.controller('mainController',function(){
// code
});
because of global variables issue so it's recommended to use the getter syntax in angular:
angular.module('app',[]);
angular.module('app').controller('mainController',function(){
//code
};
but every time I have to write the name of my application to get it so I think in another solution to do that:
'use strict';
const _APP_ = (function(){
var appName = 'app';
var result = {
init: function(dependencies){
document.body.setAttribute('ng-app',appName);
if(!dependencies || !Array.isArray(dependencies)){
dependencies = [];
}
angular.module(appName,dependencies);
},
$: function(){
return angular.module(appName);
}
};
return Object.freeze(result);
})();
now app.js file just has:
'use strict';
(function(){
_APP_.init();
})();
and to create a new controller:
'use strict';
(function(){
_APP_.$().controller('mainController',ctrl);
function ctrl(){
// code
}
})();
I'm always interested in the best practices so I need your feedback about my solution or if there is a better.

How to access parent service function from a component using Angularjs 1.5?

I have a main app module which doesn't have its own controller. It only have one service which consists of few methods. There are 2 independent components which are modules themselves. They are injected in the main module. Basically, I want to get an event inside component1 which will call the service method inside the main app module, which in returns call a method in component2.
I have passed Service Name in component1 controller but when I call it, it throws error of undefined function.
I tried to inject Service Dependency in Component1 module, but it throws error of unable to initialize component1 module.
I am also new to components concept, I think I am making some basic mistake in implementation. Furthermore, if there is another better way to call methods of one independent component from other component, then, please let me know.
main module:
(function () {
"use strict";
var app = angular.module('allocationMapsApp', ['availableTrucks','assignedJobs','ui.bootstrap']);
//cart service
app.factory("assignedJobsService", function() {
var showAssignedJobs = function(truck) {
console.log("I am in service");
};
return 1;
});
})();
component1 module:
(function () {
"use strict";
var availableTrucks = angular.module('availableTrucks', ['ui.bootstrap']);
})();
component1 code:
(function () {
"use strict";
angular.
module('availableTrucks').
component('availableTrucks', {
templateUrl: 'template.html',
controller: function AvailableTrucksController($http,assignedJobsService) {
var self = this;
self.selectTruck = function(data) {
assignedJobsService.showAssignedJobs(98);
};
}
});
})();
Component2 Module:
(function () {
"use strict";
var assignedJobs = angular.module('assignedJobs', ['ui.bootstrap']);
})();
Component2 Code:
(function () {
"use strict";
angular.
module('assignedJobs').
component('assignedJobs', {
templateUrl: 'template.html',
controller: function AssignedJobsController($http) {
var self = this;
self.fetchAssignedJobs = function () {
var url = 'index.php';
$http.get(url).then(function(response) {
console.log("Success");
console.log(response);
}, function(response) {
console.log("Failed");
console.log(response);
});
};
}
});
})();
Why throws error of undefined function.?
You are not returning assignedJobsService instance.You returning literal 1 which is dont have showAssignedJobs function.
return instance of assignedJobsService.
app.factory("assignedJobsService", function() {
var services = {}
services.showAssignedJobs = function(truck) {
console.log("I am in service");
};
return services ;
})
;
Try to give different name to component ,not same as module name.
First thing first. Avoid build your code in your module like:
angular
.module('app', [])
.controller('controllerName', function() {})
Best practice is create separate file / function to handle your controllers, services etc like:
function controllerName() {
}
angular
.module('app', [])
.controller('controllerName', controllerName);
Second thing. You are injecting assignedJobsService into your controller. Where are you exactly define this service name like that one? That can be a reason why your service is undefined.
Third this try keep name of your module and controllers etc not the same that can be tricky to deal with it later. I would recommend add prefix at the end of your component name as componentNameComponent or moduleNameModule etc.
Last thing take a look at this style guide for angularjs with es5:
https://github.com/toddmotto/angular-styleguide/tree/angular-old-es5
or if you are fell free to go with es6 what I would recommended for you take a look at this:
https://github.com/toddmotto/angular-styleguide

Angular Service injected not working

I have created and injected the service(myService) into my app (app) , but it is not working. The error implies that I have not defined the service anywhere:
Error: [$injector:unpr] Unknown provider: myServiceProvider <- myService <- myController
myService calls another service - ajaxService to do the actual http call.
The only reason I would think that myService throws the above error when trying to call it in myController is because I have another module defined in the app definition (common.components). This module has its own separate services which I am using elsewhere in my app. I am wondering if the app is searching for a definition of myService within that the common.components module instead of inside itself.
Here is my code:
- app.js
var app = angular.module('app ', ['ngRoute','common.components']);
- myService.js
var serviceId = 'myService';
angular.module('app').service(serviceId,['$q','ajaxService','$log',myService]);
function myService($q, ajaxService, $log){
var states = [];
this.getStates = function() {
var defered = $q.defer();
ajaxService.getStates().then(function(result){
states = result.data;
defered.resolve(states);
},
function(error){
deferred.reject();
});
return defered.promise;
};
}
- ajaxService.js
var serviceId = 'ajaxService';
angular.module('app',[]).service(serviceId,['$http','$log',ajaxService]);
function ajaxService($http,$log){
this.getStates = function() {
return $http.get('./json/DATA.json');
};
}
myController.js
(function(){
'use strict';
angular.module('app').controller('myController',['$scope','$log','myService',myController]);
function myController($scope,$log,myService){
$scope.states = [];
myService.getStates().then(function(states){
$scope.states = states;
});
}
})();
I have been trying to find out what is wrong for hours, but I am lost. Can someone help me with this?
I have updated my answer as you have now provided more info.
Your issue is in your ajaxService.js
Change this line
angular.module('app',[]).service(serviceId,['$http','$log',ajaxService]);
to this
angular.module('app').service(serviceId,['$http','$log',ajaxService]);
Your are recreating the app module by adding the [].

Angular is undefined in function

for a variety of reasons, my company decided to follow this model for our various objects in Angular
(function(angular) {
'use strict';
function Principal($q, $http, $cookies) {
this.$q = $q;
this.$http = $http;
this.$cookies = $cookies;
}
Principal.prototype.isIdentityResolved = function() {
return angular.isDefined(this._identity);
};
}());
The module is being defined by a master one level above this.
var Principal = require('./Principal');
var AuthServ = require('./AuthorizationService');
var SecAng = angular.module('SecAng', []);
SecAng.service('principal', Principal);
SecAng.service('authorization', AuthServ);
module.exports = SecAng;
and then browsify resolves that to a name and its included in my module in my app.js
My problem is the line return angular.isDefined(this._identity);. I keep getting errors saying that angular is undefined. Any ideas why this would be happening?
Pass angular into your self-invoking function:
(function(angular) {
'use strict';
...
}(angular));

Issues wiring up a new Angular controller module

I wonder if someone could assist me in figuring out how to wire up my new angular service module.
I keep getting the same Javascript error :
Error: [$injector] Unknown provider: gridHierarchyServiceProvider" <-- gridHierarchyService
My new services/gridHierarchyService.js file :
(function () {
'use strict';
var controllerId = 'gridHierarchyService';
angular.module('app').controller(controllerId, ['common', gridHierarchyService]);
function gridHierarchyService(common) {
var service = {
getDataSourceSchema: getDataSourceSchema
};
return service;
function getDataSourceSchema() {
var i = 1;
// TESTING...
}
}
});
and in my dashboard.js file, I attempt to inject this new service module:
(function () {
'use strict';
var controllerId = 'dashboard';
angular.module('app').controller(controllerId, ['common', 'datacontext', 'gridHierarchyService', dashboard]);
function dashboard(common, datacontext, gridHierarchyService) {
...
}
and of course I'm loading it up in my index.html:
<!-- app Services -->
<script src="app/services/datacontext.js"></script>
<script src="app/services/gridHierarchyService.js"></script>
<script src="app/services/directives.js"></script>
However, I'm clearing missing something here.
I also tried mimicking my datacontext.js service, using the .factory() call:
angular.module('app').factory(serviceI,d [...]);
but it doesn't work.
========== UPDATE !!! ============
I'm happy to say it was a very easy fix, and thanks to the community here !
WORKING SERVICE :
(function () {
'use strict';
var serviceId = 'gridHierarchyService';
angular.module('app').factory(serviceId, ['common', gridHierarchyService]);
function gridHierarchyService(common) {
var service = {
getDataSourceSchema: getDataSourceSchema
};
return service;
function getDataSourceSchema() {
var i = 1;
i = 2;
}
}
})();
I see that you are defining your controllers inside anonymous functions but that you never execute those anonymous functions.
Your code:
(function(){
//declarations
alert('You will never see me because I do not execute');
});
Fixed code (notice the parens at the end):
(function(){
//declarations
alert('You can see me!');
})();
See the above code run here: http://jsfiddle.net/wilsonjonash/cDBc7/
See more about the module pattern here:
http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
Also, you were right to try factory for a service. To make your gridHierarchyService into a service (rather than a controller), just change controller to factory or service in
var controllerId = 'gridHierarchyService';
angular.module('app').controller(controllerId, ['common', gridHierarchyService]);
Hope that does the trick for you.

Resources