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);
}
}
}]);
Related
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.
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
I have a service which get data from a file(path is given by the controller) and return a promise - then another service that create a object with properties using the returned data from the last service.
My problems are:
The getDataService runs before controller so it has no path from which to fetch data => nothing in return(an error)
Provider 'GetDataService' must return a value from $get factory method.
I need to keep this structure because I'll have more controllers with different paths to give
I'm also opened to other solutions but I need to make sure that datas are loaded before the template get populated. I've tried to call SetProperties service first with getData service into it - but still getData.js is executed first
getdata Service
angular.module('myApp').factory('GetDataService',['$http', function($http) {
var getData = function(path){
return $http.get(path).then(function(result) {
return result.data;
});
};
}]);
setProperties service
angular.module('myApp').service('PageProperties',['$http', function($http) {
this.setProps = function(page, data) {
some code here
var properties = {
isCenterActive : isActive_val,
//header elements
titleClass : page,
title : data.titles[page],
//footer elements
leftLink : leftLink_val,
leftFooterClass: leftLink_val,
leftTitle: data.titles[leftLink_val],
centerLink : centerLink_val,
centerFooterClass: data.titles[centerLink_val],
centerTitle : centerTitle_val,
rightLink : rightLink_val,
rightFooterClass: rightLink_val ,
rightTitle : data.titles[rightLink_val],
}
return properties;
}
}]);
controller
angular.module('myApp', [])
.controller('meniuController', ['$http', '$stateParams', '$scope', 'GetDataService', 'PageProperties',
function($http, $stateParams, $scope, GetDataService, PageProperties){
var page = "meniu";
$scope.language = $stateParams.lang;
var path = '_global/views/services/json/' + $stateParams.lang + '_data.json';
/*PageProperties.setProps(page, path).then(function(data){
//some code here
});*/
GetDataService.getData(path).then(function(data){
$scope.props = PageProperties.setProps(page, data);
}).catch(function(){
$scope.error = 'Unable to get data';
});
}])
Thanks in advance!!
The error says your GetDataService provider (defined as factory) doesn't return anything
angular.module('myApp').factory('GetDataService',['$http', function($http) {
var getData = function(path){
return $http.get(path).then(function(result) {
return result.data;
});
};
// you need to actually return something
return { getData: getData };
}]);
Then you can make your PageProperties use GetDataService
angular
.module('myApp')
.service('PageProperties',['GetDataService', function(GetDataService) {
this.getProperties = function(path) {
return GetDataService.getData(path).then(/*transform here*/)
}
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.
I'm new in angularJS and I got a small problem which is :
(i'll explain some details)
I have a SQL database which is deployed in Azure and I get the data from web services.
when I want to retrieve data from the database and expose it in the view , it works.
this is the controller :
var app = angular.module('ngdemoApp.controllers', []);
app.controller('CustomerViewCtrl', ['$scope', '$routeParams', 'ShowCustomerFactory','LikeProfilCustomerFactory','ShowManagerFactory',
function ($scope, $routeParams, ShowCustomerFactory,LikeProfilCustomerFactory,ShowManagerFactory) {
$scope.incrementLikeProfil = function (id) { LikeProfilCustomerFactory.likeProfil({id:$scope.customer.Id});
$scope.customer = ShowCustomerFactory.show({id: $routeParams.id});
}
$scope.customer = ShowCustomerFactory.show({id: $routeParams.id});
}]);
notice that the customer is in the database so it has properties in other word if I do {{customer.Id}} this expression shows me the value in the view.
However, when I want to use the $scope.customer in the controller like this
app.controller('CustomerViewCtrl', ['$scope', '$routeParams', 'ShowCustomerFactory','LikeProfilCustomerFactory','ShowManagerFactory',
function ($scope, $routeParams, ShowCustomerFactory,LikeProfilCustomerFactory,ShowManagerFactory) {
$scope.incrementLikeProfil = function (id) {
LikeProfilCustomerFactory.likeProfil({id:$scope.customer.Id});
$scope.customer = ShowCustomerFactory.show({id: $routeParams.id});
}
$scope.customer = ShowCustomerFactory.show({id: $routeParams.id});
$scope.test = $scope.customer.Id;
}]);
the $scope.test cannot be filled by $scope.customer.Id, at the same time the $scope.customer is filled and the view can display the value of customer but when I want to display the $scope.test in the view, i didn't get any responce.
Is there any solution ? Thank you
$scope.customer = ShowCustomerFactory.show({id: $routeParams.id});
If the above statement is making a service request and fetching data from server. This will be async and won't be available.
But in the next statement itself, you are setting
$scope.test = $scope.customer.Id;
At this point of time, $scope.customer may be undefined. That's why you're not getting the value.
You must put this statement in the then() function of promise $scope.test = $scope.customer.Id;
So in your service, return promise using $http or $q. And in your controller:
ShowCustomerFactory.show({id: $routeParams.id}).then(function(data) {
$scope.customer = data;
$scope.test = $scope.customer.id;
});
Another workaround would be :
Initially set
$scope.customer = {};
Also here is my service I use $resource :
services.factory('ShowCustomerFactory', function ($resource) {
return $resource(url + '/customerService/getCustomer?id=:id', {}, {
show: { method: 'GET',params: {id: '#id'} }
});
});