injecting service into controller not working - angularjs

Am new to angularjs. I am trying to use angular service to post data but its throwing below error
angular.js:12520 Error: [$injector:unpr] Unknown provider: frontendServiceddProvider <- frontendServicedd <- CustSignupCtrl
service.js
app.service('frontendService', function frontendService ($http, $q, $rootScope){
var list = this;
list.registerCust = function(data){
var defer = $q.defer();
$http({
url: $rootScope.endPoint,
method: "POST",
data: data
})
.success(function(res){
console.log("Successfull!");
defer.resolve(res);
})
.error(function(err, status){
console.log("Failed !");
})
return defer.promise;
}
return list;
});
customer_signup.js
app.controller('CustSignupCtrl', ['$scope', '$filter','frontendService', '$http', 'editableOptions', 'editableThemes','notify','notification','$appConstants',
function('$scope', '$filter','frontendService', '$http','editableOptions', 'editableThemes','notify','notification','$appConstants'){
$scope.pw1 = '';
$scope.registerCustomer = function (data) {
return frontendService.registerCust(data)
}
$scope.signupcustomer = function(){
var payload= {
first_name: $scope.custForm.fname,
last_name: $scope.custForm.lname,
phone: $scope.custForm.phone,
email:$scope.custForm.email,
username:$scope.custForm.username,
password:$scope.custForm.pw1,
usertype:3
}
console.log("inside function");
$scope.registerCustomer(payload).then(function(data){
notification.success(data.result);
},function(err){
notification.error("Error: contact system admin");
});
}
}
])
I have given reference of both js files in index.html.. not getting where am doing wrong.. can anyone help

app.controller('CustSignupCtrl', ['$scope', '$filter', 'frontendService', '$http', 'editableOptions', 'editableThemes','notify','notification','$appConstants',
function($scope, $filter, frontendService, $http, editableOptions, editableThemes, notify, notification, $appConstants){
$scope.pw1 = '';
});
Whatever you inject into controller, should be in the same order.
Remove quotes accross the injectables inside function.

This can be a dependency injection mismatch sort of problem
AngularJS injects object into the function as it sees them inside []
For example if you declare a function inside your js file, say like this
var app = angular.module('app',[]);
app.controller('maincntrl',function($scope){
});
var search = function($scope,searchtext,searchfilters,searchareas)
{
return 'result'
}
console.log(angular.injector.annotate(search));
The result you shall get in your console will be
["$scope","searchtext","searchfilters","searchareas"]
AngularJS parses the function parameters as an array
It goes through each array elements and the moment it sees "$scope", it injects scope object into that position
Now the syntax which you have used is basically used for minification
So according to your declaration
app.controller('CustSignupCtrl', ['$scope','frontendService', '$filter','frontendService', '$http', 'editableOptions', 'editableThemes','notify','notification','$appConstants',
function('$scope', '$filter','frontendService', '$http','editableOptions', 'editableThemes','notify','notification','$appConstants'){
});
So
$scope--> shall be injected into $scope
frontendService-->shall be injected into $filter
$filter--> shall be injected into frontendService
.
.
.
so on
Also the errors(which you mentioned in comments) are occurring because you have declared function parameters as strings in which case the dependency injection is not happening. Fixing these things shall solve your problem

Related

Using AngularJS Service in Controller

Service:
app.service('myService', ['$scope', '$timeout', function($scope, $timeout){
return {
fn: function(messageTitle, messageContent) {
$timeout(function() {
$scope.fadeMessageSuccess = true;
}, 3000);
}
}
}]);
Controller:
app.controller("AccountCtrl", ["$scope", "Auth", "$timeout", "myService",
function($scope, Auth, $timeout, myService) {
myService.fn();
$scope.createUser = function() {
$scope.message = null;
$scope.error = null;
// Create a new user
Auth.$createUserWithEmailAndPassword($scope.accountEmailAddress, $scope.accountPassword)
.then(function(firebaseUser) {
$scope.message = "User created with uid: " + firebaseUser.uid;
console.log($scope.message);
}).catch(function(error) {
$scope.error = error;
console.log($scope.error);
});
};
}
]);
I'm trying to create a service so that I can use a function in multiple controllers but I'm have trouble getting this first one working. This is the error message I'm getting in console:
angular.js:13550Error: [$injector:unpr]
Just an observation: doesn't look like you're passing anything to the function when you're calling it. And not sure if you're wanting to add any more functionality to the service, but I think you can return the function directly and just call "myService(title, content);". But I don't think those issues would cause what you're encountering.
It looks like you were trying to return an object (a la the .factory() function) when you were trying to use .service(). Here is a dead simple explanation for .factory, .service, and .provider.
As pointed out by user2341963, injecting $scope into a service doesn't make much sense.
Also, are you sure all of your dependencies are defined and available to Angular?
Here is an example Plunkr of using a service in a controller.

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

Angularjs cannot get data from service

I'm trying to pass data from one controller to another using a service, however no matter what I'm trying it always returns 'undefined' on the second controller. Here is my service :
app.service('myService', ['$rootScope', '$http', function ($rootScope, $http) {
var savedData = {}
this.setData = function (data) {
savedData = data;
console.log('Data saved !', savedData);
}
this.getData = function get() {
console.log('Data used !', savedData);
return this.savedData;
}
}]);
Here is controller1 :
.controller('HomeCtrl', ['$scope','$location','$firebaseSimpleLogin','myService','$cookies','$window', function($scope,$location, $firebaseSimpleLogin, myService, $cookies, $window) {
loginObj.$login('password', {
email: username,
password: password
})
.then(function(user) {
// Success callback
console.log('Authentication successful');
myService.setData(user);
console.log('myservice:', myService.getData()); // works fine
}]);
And then controller2:
// Dashboard controller
.controller('DashboardCtrl', ['$scope','$firebaseSimpleLogin','myService',function($scope,$firebaseSimpleLogin, $location, myService) {
console.log('myservice:', myService.getData()); //returns undefined
}]);
That is simple code, unfortunately I've been struggling for a few hours now, any suggestion ? Thanks.
Created a fiddle here:
http://jsfiddle.net/frishi/8yn3nhfw/16
To isolate the problem, can you remove the dependencies from the definition for myService and see if that makes it work? Look at the console after you load the fiddle.
var app = angular.module('app', [])
.service('myService', function(){
this.getData = function(){
return "got Data";
}
})
I assume the issue is that you are returning this.savedData in the service. Try returning savedData.
this behaves different in Javascript than in other languages.

Pass parameter from controller to service in Angular

I'm trying to pass a parameter from a controller to service in Angular. Here is the controller:
angular.module('CityCtrl', []).controller('CityController',['$scope', '$http', function($scope,$http,CityService){
$scope.data = "unknown";
$http.jsonp('http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&callback=JSON_CALLBACK').success(function(data){
$scope.data=data;
});
console.log($scope.name);
if($scope.name){
$scope.weather = CityService.get($scope.name);
}
$scope.update = function (zip) {
$scope.zip = zip;
console.log(zip);
$scope.weather = CityService.get({zip: zip});
alert("Hello, " + zip);
}
}]);
and here is the service:
angular.module('CityService', []).factory('City', '$scope'['$http', function($scope,$http) {
return {
get : function() {
return $http.get('/cities/' + zip);
}
}
}]);
When I check the console it is logging the correct value, however, when it tried to run the service it says:
Cannot read property 'get' of undefined
For some reason the zip is not being passed to the service. Any idea where the disconnect is?
You would need to inject City Service, When using explicit dependency annotation, it is all or none rule, you cannot just specify part of your dependencies.
angular.module('CityCtrl', []).controller('CityController',
['$scope', '$http', 'City'
function($scope, $http, City){
Also you cannot inject $scope in a factory (It is available for injection only to controllers, for directive you get it as an argument in the linking function) and looks like you do not need as well.
angular.module('CityService', []).factory('City', ['$http', function($http) {
return {
get : function(zip) {
return $http.get('/cities/' + zip);
}
}
}]);

Problems using $http inside a Service

I have a basic data Service which will be used across Controllers. But I'm having an issue grabbing some data that's been added via $http.
Service:
angular.module('core').service('FormService', ['$http', function($http) {
var _this = this;
_this.dropdownData = {
contactTimes: ['Anytime','Morning','Afternoon','Evening'],
industries: {},
};
$http.get('/json').success(function(resp){
_this.dropdownData.industries = resp.industries;
});
}]);
Controller:
angular.module('core').controller('SignupController', ['$scope', '$http', '$state', 'FormService', function($scope, $http, $state, FormService) {
console.log(FormService.dropdownData); // Shows full object incl industries
console.log(FormService.dropdownData.industries); // empty object {}
}]);
How do I get FormService.dropdownData.industries in my controller?
Create a service like below
appService.factory('Service', function ($http) {
return {
getIndustries: function () {
return $http.get('/json').then(function (response) {
return response.data;
});
}
}
});
Call in controller
appCtrl.controller('personalMsgCtrl', ['$scope', 'Service', function ($scope, Service) {
$scope.Industries = Service.getIndustries();
}]);
Hope this will help
Add a method to your service and use $Http.get inside that like below
_this.getindustries = function (callback) {
return $http.get('/json').success(function(resp){
_this.dropdownData.industries = resp.industries;
callback(_this.dropdownData)
});
};
In your controller need to access it like below.
angular.module('core').controller('myController', ['$scope', 'FormService', function ($scope, FormService) {
FormService.getDropdownData(function (dropdownData) {
console.log(dropdownData); // Shows full object incl industries
console.log(dropdownData.industries); // object {}
});
} ]);
Given that your console log shows the correct object, that shows your service is functioning properly. Only one small mistake you have made here. You need to access the data attributes in your return promise.
angular.module('core').service('FormService', ['$http', function($http) {
var _this = this;
_this.dropdownData = {
contactTimes: ['Anytime','Morning','Afternoon','Evening'],
industries: {},
};
$http.get('/json').success(function(resp){
//note that this is resp.data.industries, NOT resp.industries
_this.dropdownData.industries = resp.data.industries;
});
}]);
Assuming that you're data is indeed existing and there are no problems with the server, there are quite a few possible solutions
Returning a promise
angular.module('core').service('FormService', ['$http', function($http) {
var _this = this;
_this.dropdownData = {
contactTimes: ['Anytime','Morning','Afternoon','Evening'],
industries: {},
};
_this.dropdownData.industries = $http.get('/json');
}]);
//Controller
FormService.industries
.then(function(res){
$scope.industries = res.industries
});
Resolving with routeProvider / ui-route
See: $http request before AngularJS app initialises?
You could also write a function to initialize the service when the application starts running. At the end of the day, it is about waiting for the data to be loaded by using a promise. If you never heard about promises before, inform yourself first.
The industries object will be populated at a later point in time when the $http call returns. In the meantime you can still bind to the reference in your view because you've preserved the reference using angular.copy. When the $http call returns, the view will automatically be updated.
It is also a good idea to allow users of your service to handle the event when the $http call returns. You can do this by saving the $promise object as a property of industries:
angular.module('core').service('FormService', ['$http', function($http) {
var _this = this;
_this.dropdownData = {
contactTimes: ['Anytime','Morning','Afternoon','Evening'],
industries: {},
};
_this.dropdownData.industries.$promise = $http.get('/json').then(function(resp){
// when the ansyc call returns, populate the object,
// but preserve the reference
angular.copy( resp.data.industries, _this.dropdownData.industries);
return _this.dropdownData.industries;
});
}]);
Controller
app.controller('ctrl', function($scope, FormService){
// you can bind this to the view, even though the $http call has not returned yet
// the view will update automatically since the reference was preserved
$scope.dropdownData = FormService.dropdownData;
// alternatively, you can hook into the $http call back through the $promise
FormService.dropdownData.industries.$promise.success(function(industries) {
console.log(industries);
});
});

Resources