Angular Service injected not working - angularjs

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 [].

Related

how to get variable from different AngularJS file?

How is it possible to get $scope variable from different file (with different module)? For example, I have two files - index.js and login.js, I want to get username from login.js in index.js. I tried to use services but couldn't achieve that goal. The controller doesn't see service in another angular file.
Codes partially are given below:
bookApp.controller('bookListCtrl', ['sharedProperties', function($scope, $http, sharedProperties) {
'use strict';
$scope.name = "Alice";
console.log("in book controller");
console.log("getting login name: "+sharedProperties.getProperty());
and
var authentication = angular.module('authentication', []);
authentication.service('sharedProperties', function () {
var property = 'First';
return {
getProperty: function () {
return property;
},
setProperty: function(value) {
property = value;
}
};
});
I got this exception -
angular.min.js:63 Error: Unknown provider: authentication.sharedPropertiesProvider <- authentication.sharedProperties
at Error (native)
at
There are 2 problems in the given implementation. The first problem is that the module 'authentication' needs to be a dependency for the consuming modules. The second problem is in the declaration of bookListCtrl. It needs to be defined as follows.
bookApp.controller('bookListCtrl', ['$scope','$http','sharedProperties', function($scope, $http, sharedProperties){
}]);
Can you give an example how you've used services?
Normally if you define controllers like:
app.controller('LoginController', ['UserService', function($scope) {
$scope.someMethod = function(){
// push information to service
UserService.username = $scope.username;
}
}]);
app.controller('IndexController', ['UserService', function($scope) {
// pull information from service
$scope.username = UserService.username;
}]);
It should work. I must suggest you thou to use Controller as instead of $scope. More info here: https://docs.angularjs.org/api/ng/directive/ngController

how to inject factory into another factory in Angular

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.

Unknown provider in .config() with custom Provider

I've got this in app.js:
angular.module('App',[]).config(['TranslationProvider', function (TranslationProvider) {
//codes...
}]);
And this service in another file:
angular.module('App')
.provider('Translation', function() {
var translations = {foo:"bar"}
this.$get = function(){
return translations;
};
});
No 404 error with the service js file, but when angular injector try to instantiate it gives me this error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module App due to:
Error: [$injector:unpr] Unknown provider: TranslationProvider
I've followed the angjs documentation https://docs.angularjs.org/guide/providers
It seems to be a bug in Angular 1.2.x. The order of the calls matter. When you call provide before config it works. It also works with Angular 1.3.x regardless of the order.
You are almost there.
First the config:
angular.module('App')
.config(["TranslationProvider", function(theProvider) {
console.log("in config" + theProvider)
theProvider.setName("some name");
}]);
The error you were having was due to you using the constructor function as an argument.
Now your provider:
angular.module('App')
.provider('Translation', function TranslationProvider() {
var translations = {foo:"bar", name:""};
var dynamicName;
this.setName = function(configName) {
dynamicName = configName;
};
this.$get = function(){
translations.name = dynamicName;
return translations;
};
});
Also note that an anonymous function (i.e. .provider('Translation', function () {) could also have been used and the code would have worked just as well.
Using it all in a controller:
angular.module('App')
.controller('MyController', [
'$scope',
'Translation',
function ($scope,
translationProvider) {
$scope.modal = {};
$scope.projects = [];
console.log(translationProvider)
$scope.foo = translationProvider;
}]);

Angularjs - Invoke Function from module.config

I have a code of
var viewerAngular = angular.module('ngAppDemo', ['restangular','btford.socket-io'])
.config(function(RestangularProvider) {
$.get('../config/config.xml',
function(data) {
$(data).find('contentserver').each(function() {
serverDetails.contentserver = assignServerDetails($(this));
var restprovider = RestangularProvider;
restprovider.setBaseUrl("http://"+serverDetails.contentserver.ip+":"+serverDetails.contentserver.port+"\:"+serverDetails.contentserver.port);
//$scope.init();
});
});
I need to invoke function init(), after reading the config(../config/config.xml) file.
I got an error of ReferenceError: $scope is not defined.
How can I add $scope in module.config? Or How can I call function from config?
If you need to add something to every scope in config, you can use $rootScope, but it's better practice to create a service for that data.
You can not ask for instance during configuration phase - you can ask only for providers.
var app = angular.module('app', []);
// configure stuff
app.config(function($routeProvider, $locationProvider) {
// you can inject any provider here
});
// run blocks
app.run(function($rootScope) {
// you can inject any instance here
});
See http://docs.angularjs.org/guide/module for more info.
var viewerAngular = angular.module('ngAppDemo', ['restangular','btford.socket-io'])
.config(function(RestangularProvider) {
$.get('../config/config.xml',
function(data) {
$(data).find('contentserver').each(function() {
serverDetails.contentserver = assignServerDetails($(this));
var restprovider = RestangularProvider;
restprovider.setBaseUrl("http://"+serverDetails.contentserver.ip+":"+serverDetails.contentserver.port+"\:"+serverDetails.contentserver.port);
var Scope=angular.element(document.querySelector('[ng-controller="controllerName"]')).scope();
Scope.init();
});
});

AngularJS use custom services in custom providers

I have a simple question about the dependency injection in Angular. I create custom services in order to use them within each other. Unfortunately I receive errors the way I was trying it. This is my Code:
var myApp = angular.module('app', []);
myApp.service('$service1', ['$rootScope', function($rootScope) {
this.test = function() {
console.log('service1');
};
}]);
myApp.provider('$service2', ['$service1', function($service1) {
var service = 'service2';
this.registerService = function(mytext) {
service = mytext;
};
this.$get = function() {
var that = {};
that.test = function() {
console.log(service);
};
return that;
};
}]);
myApp.config(['$service2Provider', function($service2Provider) {
$service2Provider.registerService('changed service2');
}]);
myApp.controller('AppCtrl', ['$rootScope', '$service1', '$service2',
function($rootScope, $service1, $service2) {
$service1.test();
$service2.test();
}]);
Error: [$injector:modulerr] Failed to instantiate module app due to:
[$injector:unpr] Unknown provider: $service1
http://errors.angularjs.org/1.2.0-rc.2/$injector/unpr?p0=%24service1
If you remove the dependency of $servic1 in $service2 it will work, but why?
The code is mostly right, except you have to inject service dependencies in $get, not in the provider constructor function, like this:
myApp.provider('$service2', function() {
var service = 'service2';
this.registerService = function(mytext) {
service = mytext;
};
this.$get = ['$service1', function($service1) {
var that = {};
that.test = function() {
console.log(service);
};
return that;
}];
});
It appears that provider can not inject such a dependency. If you rewrite $service2 using a factory, it works:
myApp.factory('$service2', ['$service1', function($service1) {
var that = {};
that.test = function() {
$service1.test();
console.log('service2');
};
return that;
}]);
See this plunker: http://plnkr.co/edit/JXViJq?p=preview
Also I believe that service names starting with a $ a reserved for AngularJS and its extensions. Use names without the $ at the beginning for services defined by your application.

Resources