I'm approaching AngularJS and I want to get data from a database. I succeeded in doing this
angular.module("myApp")
.controller("listaUtentiCtrl", function($scope, $http) {
$http.get("backListaUtenti.php").success(function(data) { $scope.utenti=data } )
});
but I'd like to use a factory / service in order use the data from multiple controllers (but is not working)
angular.module("myApp")
.factory("utentiService", function($http,$q) {
var self = $q.defer();
$http.get("backListaUtenti.php")
.success(function(data){
self.resolve(data);
})
.error(function(){
alert("Error retrieving data!");
})
return self.promise;
});
angular.module("myApp")
.controller("utenteCtrl", function($scope, $routeParams, utentiService, filterFilter) {
var userId = $routeParams.userId;
$scope.utente = filterFilter(utentiService.utenti, { id: userId })[0];
});
angular.module("myApp")
.controller("listaUtentiCtrl", function($scope, utentiService) {
$scope.utenti = utentiService.utenti;
});
Where am I failing?
The problem is in your service implementation. Here is your code refactored:
angular.module("myApp")
.factory("utentiService", function($http) {
return {
getData: function () {
return $http.get("backListaUtenti.php").then(function (response) {
return response.data;
});
}
};
});
angular.module("myApp")
.controller("utenteCtrl", function($scope, $routeParams, utentiService, filterFilter) {
var userId = $routeParams.userId;
utentiService.getData().then(function(data) {
$scope.utente = filterFilter(data, { id: userId })[0];
});
});
angular.module("myApp")
.controller("listaUtentiCtrl", function($scope, utentiService) {
utentiService.getData().then(function (data) {
$scope.utenti = data;
});
});
If your data is static you can cache the request and avoid unnecessary requests like this:
$http.get("backListaUtenti.php", { cache: true });
Related
I have two factories in my angular app.
app.factory('FavoritesArtists',['$http', '$q', 'UserService', function($http, $q, UserService){
var deferred = $q.defer();
var userId = UserService.getUser().userID;
$http.get('http://myurl.com/something/'+userId)
.success(function(data) {
deferred.resolve(data);
})
.error(function(err) {
deferred.reject(err);
});
return deferred.promise;
}]);
And I have a value I get from another factory :
var userId = UserService.getUser().userID;
But I doesn't update when the UserService.getUser() is changed, the view changes with $watch, but I don't know how it work inside a factory.
Any help is welcome, thanks guys !
Anyone ?
app.factory('FavoritesArtists',['$http', '$q', 'UserService', function($http, $q, UserService){
var deferred = $q.defer();
$http.get('https://homechefhome.fr/rise/favorites-artists.php?user_id='+userId)
.success(function(data) {
deferred.resolve(data);
})
.error(function(err) {
deferred.reject(err);
});
return deferred.promise;
}]);
I simply need to make userId variable dynamic..
A better design pattern will be this
app.factory('UserService',
['$http', function($http) {
var getUser = function() {
return http.get("url_to_get_user");
};
return {
getUser: getUser
};
}]);
app.factory('ArtistService',
['$http', '$q', 'UserService', function($http, $q, UserService) {
var getFavoriteArtists = function() {
UserService.getUser().then(function(response) {
var userId = response.data.userID;
return $http.get('http://myurl.com/something/' + userId);
}, function() {
//passing a promise for error too
return $q.reject("Error fetching user");
});
};
return {
getFavoriteArtists: getFavoriteArtists
};
}]);
Now call it in controller like,
ArtistService.getFavoriteArtists().then(function(response) {
//do something with response.data
}, function(response) {
//log error and alert the end user
});
i have my authservice as given below ,
myApp.factory('Authentication',
['$rootScope', '$location', 'URL', '$http', '$q',
function ($rootScope, $location, URL, $http, $q) {
var myObject = {
authwithpwd: function (user) {
var dfd = $q.defer();
$http
.post('Mart2/users/login', {email: user.email, password: user.password})
.then(function (res) {
return dfd.resolve(res.data);
}, function (err) {
return dfd.reject(err.data);
});
return dfd.promise;
} //login
};
return myObject;
}]); //factory
And i'm using that service in user service as follows :
myApp.factory('UserService',
['$rootScope', '$location', 'URL', '$http', '$q', 'Authentication',
function ($rootScope, $location, URL, $http, $q, $Authentication) {
var myObject = {
login: function (user) {
$Authentication.authwithpwd(user).then(function (regUser) {
console.log(regUser);
}).catch(function (error) {
$rootScope.message = error.message;
});
},
getUserToken: function () {
return $rootScope.currentUser.apiKey;
},
isLogged: function () {
if ($rootScope.currentUser) {
return true;
} else {
return false;
}
}
//login
};
return myObject;
}]); //factory
I am very new to angular js . While writing service and calling that service from controller i have put a console debug in user service which is showing its returning object .i am getting object if i do console.log(regUser) ? any idea why ?
To get the object you need to do change your myObject declaration. Basically you need to return a promise from the login function and then write a callback to get the resolved data.
myApp.factory('UserService',
['$rootScope', '$location', 'URL','$http','$q','Authentication',
function($rootScope,$location, URL,$http,$q,$Authentication) {
var myObject = {
login: function(user) {
var defer = $q.defer();
$Authentication.authwithpwd(user).then(function(regUser) {
console.log(regUser);
defer.resolve(regUser);
}).catch(function(error) {
$rootScope.message = error.message;
defer.reject(regUser);
});
return defer.promise;
},
getUserToken:function() {
return $rootScope.currentUser.apiKey;
},
isLogged:function() {
if($rootScope.currentUser){
return true;
} else {
return false;
}
}//login
};
return myObject;
}]); //factory
To extract the object from controller or from some other service you need to write a callback
UserService.login(user)
.then(function (data) {
$scope.data = data;
}, function (error) {
$scope.error = error;
});
Also in the Authentication service you can just do a 'dfd.resolve' instead of 'return dfd.resolve'; since you are already returning the dfd.promise.
I have created a fiddler here
I am trying to create a service that passes data to controller.
I cannot see any errors in the console but yet the data won't show. What exactly am I doing wrong?
Service
app.service('UsersService', function($http, $q) {
var url = '/users';
var parsePromise = $q.defer();
$http.get(url).success(function(data) {
parsePromise.resolve(data);
});
return parsePromise.promise;
});
Controller
app.controller('contactsCtrl',
function($scope, $routeParams, UsersService) {
// Get all contacts
UsersService.get().then(function(data) {
$scope.contacts = data;
});
});
success is now deprecated.
app.service('UsersService', function($http) {
var url = '/users';
this.get = function() {
return $http.get(url).then(function(response) {
return response.data;
});
}
});
you are referring to UsersService.get(), so you must define the .get() function to call:
app.service('UsersService', function($http, $q) {
var url = '/users';
this.get = function() {
var parsePromise = $q.defer();
$http.get(url).success(function(data) {
parsePromise.resolve(data);
});
return parsePromise.promise;
}
});
I'm moving my code from the .controller to a factory
here is the code that works from the controller
.controller('ChatsCtrl', function ($scope, $http, $rootScope) {
$http.get('http://<my_ip>:<my_port>/chats', { params: { user_id: $rootScope.session } }).success(function (response) {
$scope.chats = response;
});
})
I want this to be refactored to a factory so the controller looks like this
.controller('ChatsCtrl', function ($scope, Chats) {
$scope.chats = Chats.all();
})
So the factory is like this
.factory('Chats', function() {
return {
all: function ($scope, $http, $rootScope) {
return $http.get('http://<my_ip>:<my_port>/chats', { params: { user_id: $rootScope.session } }).success(function (response) {
$scope.chats = response;
});
}
};
});
So when I move the code to the factory it doesn't pull anything from my database. I have referenced the 'Chats' factory in the controller but it doesn't seem to pull the data through.
Return the promise to set and assign it to the scope in the controller. So more like this.
.controller('ChatsCtrl', function ($scope, Chats) {
Chats.all().success(function (data) {
$scope.chats = data;
})
})
.factory('Chats', function($http, $rootScope) {
return {
all: function () {
return $http.get('http://<my_ip>:<my_port>/chats',
{ params: { user_id: $rootScope.session } })
}
};
});
You can return a promise from the factory and do .success in the controller(optionally with a cache in the factory if your data doesn't change)
.factory('Chats', function() {
return {
all: function ($scope, $http, $rootScope) {
return $http.get('http://<my_ip>:<my_port>/chats', { params: { user_id: $rootScope.session } })
}
};
});
.controller('ChatsCtrl', function ($scope, Chats) {
Chats.all().success(function (response) {
$scope.chats = response;
});
})
When using an AngularJS service to try and pass data between two controllers, my second controller always receives undefined when trying to access data from the service. I am guessing this is because the first service does a $window.location.href and I'm thinking this is clearing out the data in the service? Is there a way for me to change the URL to a new location and keep the data persisted in the service for the second controller? When I run the code below the alert in the second controller is always undefined.
app.js (Where Service is Defined)
var app = angular.module('SetTrackerApp', ['$strap.directives', 'ngCookies']);
app.config(function ($routeProvider)
{
$routeProvider
.when('/app', {templateUrl: 'partials/addset.html', controller:'SetController'})
.when('/profile', {templateUrl: 'partials/profile.html', controller:'ProfileController'})
.otherwise({templateUrl: '/partials/addset.html', controller:'SetController'});
});
app.factory('userService', function() {
var userData = [
{yearSetCount: 0}
];
return {
user:function() {
return userData;
},
setEmail: function(email) {
userData.email = email;
},
getEmail: function() {
return userData.email;
},
setSetCount: function(setCount) {
userData.yearSetCount = setCount;
},
getSetCount: function() {
return userData.yearSetCount;
}
};
});
logincontroller.js: (Controller 1 which sets value in service)
app.controller('LoginController', function ($scope, $http, $window, userService) {
$scope.login = function() {
$http({
method : 'POST',
url : '/login',
data : $scope.user
}).success(function (data) {
userService.setEmail("foobar");
$window.location.href = '/app'
}).error(function(data) {
$scope.login.error = true;
$scope.error = data;
});
}
});
appcontroller.js (Second controller trying to read value from service)
app.controller('AppController', function($scope, $http, userService) {
$scope.init = function() {
alert("In init userId: " userService.getEmail());
}
});
Define your service like this
app.service('userService', function() {
this.userData = {yearSetCount: 0};
this.user = function() {
return this.userData;
};
this.setEmail = function(email) {
this.userData.email = email;
};
this.getEmail = function() {
return this.userData.email;
};
this.setSetCount = function(setCount) {
this.userData.yearSetCount = setCount;
};
this.getSetCount = function() {
return this.userData.yearSetCount;
};
});
Check out Duncan's answer here:
AngularJS - what are the major differences in the different ways to declare a service in angular?