angular JS $rootScope undefined inside $http.get - angularjs

I want to retrieve data from an $http.get and put it in $rootScope :
.run
app.run(function ($rootScope, $q, $http, $timeout, stateRules) {
stateRules
.then(function (data) {
$rootScope.user = data;
console.log(data);
});
});
.service
app.service('stateRules', ['$http','$q', function($http, $q) {
var userUrl= 'api/user/';
var userService = {};
var deferred = $q.defer();
$http.get(userUrl+ "getUserName", { cache: true }).success(function (data) {
deferred.resolve(data);
});
return deferred.promise;
});
.controller
app.controller('userCtrl', ['$scope', function ( $scope) {
console.log($scope.user);
}]);
but the value of the $scope.user in my controller is undefined. Any idea how to fix it ?
Thanks

$rootScope should be injected in a service. like this.
.service('ServiceGetSVC', ['$http','$rootScope','$q',function ($http,$rootScope,$q) {....}
Or if you try to use $rootScope.user after method get. It was undefined becouse method get asynchronous. Should use deferred.
in application
ServiceGetSVC.then(data){
$rootScope.user = data;
}
service
.service('stateRules', ['$http','$q' function($http, $q) {
var deferred = $q.defer();
$http.get(communUrl + "getUserName", { cache: true }).success(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}])

Related

Passing rootScope value from one controller to another controller

I am trying to pass the value from controller to another using $rootscope what I did is first I intialize rootScope like this
app.run(function ($rootScope) {
$rootScope.emp=0 ;
});
then I am changing the value of rootScope in one of my controller like this this
app.controller("datatableController", function ($scope, DTOptionsBuilder, $http, $rootScope) {
$scope.update = function (data) {
alert(data);
$scope.message = $http.post('http://localhost:5000/api/employee/view', data).
then(function (response) {
$scope.userEdit = response.data;
$rootScope.emp=$scope.userEdit[0].id;
alert($rootScope.emp);
});
window.location.href = "updateEmployee.html";
};
});
then i am trying to access this changed $rootScope.emp value in my second controller but getting the value that i set at the time of initialization which is 0
app.controller("UpdateController", function ($scope, $http, $rootScope) {
$scope.userid=$rootScope.emp;
alert($scope.userid);
});
Try This :
app.controller("datatableController", function ($scope, DTOptionsBuilder, $http, $rootScope) {
$scope.update = function (data) {
alert(data);
$scope.message = $http.post('http://localhost:5000/api/employee/view', data).
then(function (response) {
$scope.userEdit = response.data;
$rootScope.$apply(function(){
$rootScope.emp=$scope.userEdit[0].id;
});
alert($rootScope.emp);
});
window.location.href = "updateEmployee.html";
};
});
Detailed Answer can be found here

Update data from a factory in another factory

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
});

AngularJS : returning data from service to controller

I am trying to create a service to get json and pass it to me homeCtrl I can get the data but when a pass it to my homeCtrl it always returns undefined. Im stuck.
My Service:
var myService = angular.module("xo").factory("myService", ['$http', function($http){
return{
getResponders: (function(response){
$http.get('myUrl').then(function(response){
console.log("coming from servicejs", response.data);
});
})()
};
return myService;
}
]);
My Home Controller:
var homeCtrl = angular.module("xo").controller("homeCtrl", ["$rootScope", "$scope", "$http", "myService",
function ($rootScope, $scope, $http, myService) {
$scope.goData = function(){
$scope.gotData = myService.getResponders;
};
console.log("my service is running", $scope.goData, myService);
}]);
You should return promise from getResponders function, & when it gets resolved it should return response.data from that function.
Factory
var myService = angular.module("xo").factory("myService", ['$http', function($http) {
return {
getResponders: function() {
return $http.get('myUrl')
.then(function(response) {
console.log("coming from servicejs", response.data);
//return data when promise resolved
//that would help you to continue promise chain.
return response.data;
});
}
};
}]);
Also inside your controller you should call the factory function and use .then function to get call it when the getResponders service function resolves the $http.get call and assign the data to $scope.gotData
Code
$scope.goData = function(){
myService.getResponders.then(function(data){
$scope.gotData = data;
});
};
This is an example how I did for my project, it work fine for me
var biblionum = angular.module('biblioApp', []);//your app
biblionum.service('CategorieService', function($http) {
this.getAll = function() {
return $http({
method: 'GET',
url: 'ouvrage?action=getcategorie',
// pass in data as strings
headers: {'Content-Type': 'application/x-www-form-urlencoded'} // set the headers so angular passing info as form data (not request payload)
})
.then(function(data) {
return data;
})
}
});
biblionum.controller('libraryController', function($scope,CategorieService) {
var cat = CategorieService.getAll();
cat.then(function(data) {
$scope.categories = data.data;//don't forget "this" in the service
})
});

How to change pyramid request to promises with $q

I want to change this pyramid request to promises with $q.
app.controller('Ctrl', function ($scope, $http, $q) {
$http.post('http://localhost:1235',data_post1).success(function (data){
console.log("1");
$http.post('http://localhost:1236',data_post2).success(function (data){
console.log("2");
$http.post('http://localhost:1237',data_post3).success(function (data){
console.log("3");
$http.post('http://localhost:1238',data_post4).success(function (data){
console.log("4");
});
});
});
});
}
I'm never use $q before.
so best practice would be to pull the http requests out of the controller
so if you had a factory like
app.factory("fooSrvc", ["$q", "$http", function($q, $http){
return {
data1: function(postData){
var deferred = $q.defer();
$http.post("", postData).success(function(results){
deferred.resolve(results);
});
return deferred.promise;
},
data2: function(postData){
var deferred = $q.defer();
$http.post("", postData).success(function(results){
deferred.resolve(results);
});
return deferred.promise;
}
};
}]);
then your controller could look like
app.controller("Ctrl", ["$scope", "fooSrvc", function($scope, fooSrvc){
fooSrvc.data1(dataTopost).then(function(results){
// do something with it here possibly
fooSrvc.data2(moreDataToPost).then(function(moreResults){
// do something with it here possibly
});
});
}]);

AngularJS pass parameter from Controller to Service

I don't know how to pass data from the controller to the service as method arguments... I need to set in the controller the headers variable which is later added to the service which adds this later on to the http call
controller
angular.module('userControllers', []).
controller('userController', ['$scope', '$q', 'Users', '$location',
function($scope, $q, Users, $location) {
$scope.viewUser = function(userId) {
$location.path('/users/'+userId);
};
$scope.createUser = function () {
$location.path('/users/create');
};
headers = {service:'json',resource:'users'};
$scope.users = Users.query(headers);
$scope.users.$promise.then(function(result){
$scope.users = result;
});
}]);
service
angular.module('userServices', ['ngResource']).
factory('Users', ['$resource', '$q', function($resource, $q){
var factory = {
query: function (headerParams) {
var data = $resource('http://localhost:8080/gateway', {}, {
query: {
method: 'GET',
isArray: true,
headers: headerParams
}
});
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);
In this setup I'm getting Error: [$injector:unpr] Unknown provider: UserProvider <- User ... not really sure how to fix this one out ...
Later edit : code cleanup... posted full code and new error
TypeError: Cannot read property 'then' of undefined
at new <anonymous> (http://localhost/frontend-pdi-angular-js/js/controllers/users.js:16:38)
at invoke (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:3918:17)
at Object.instantiate (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:3929:23)
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:7216:28
at link (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.js:913:26)
at nodeLinkFn (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:6648:13)
at compositeLinkFn (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:6039:13)
at publicLinkFn (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:5934:30)
at boundTranscludeFn (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:6059:21)
at controllersBoundTransclude (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js:6669:18) <div ng-view="" class="ng-scope">
Later edit #2 : some working code, but using no ngResource whatsoever
angular.module('userControllers', ['userServices']).
controller('userController',
['$scope', '$q', 'Users', '$location', '$http',
function($scope, $q, Users, $location, $http) {
headerParams = {service:'json',resource:'users'};
$scope.users = $http({method: 'GET', url: 'http://localhost:8080/gateway', headers: headerParams, isArray:true}).
success(function(data, status, headers, config) {
$scope.users = data;
console.log(data);
}).
error(function(data, status, headers, config) {
console.log(status);
});
}]);
As others mentioned, you are using a non-existent reference to a provider ($promise) in your code. By simply setting the deferred to $scope.users and then acting on the 'then' of that deferred, you can solve this problem.
You can also simplify it a bit. You are setting the deferred on the $scope object and then you're overwriting that with the resolved value of the deferred. So you can do this instead:
Users.query(headers).then(function(result){
$scope.users = result;
});
if you want to assign the deferred to a separate variable:
var deferred = Users.query(headers);
deferred.then(function(result){
$scope.users = result;
});
angular.module('userControllers', ['userServices']).
controller('userController',
['$scope', '$q', 'Users', '$location',
function($scope, $q, Users, $location) {
headers = {service:'json',resource:'users'};
Users.query(headers).then(function(result){
$scope.users = result;
});
}])
angular.module('userServices', ['ngResource']).
factory('Users', ['$resource', '$q', function($resource, $q){
var factory = {
query: function (headerParams) {
var data = $resource('http://localhost:8080/gateway', {}, {
query: {
method: 'GET',
isArray: true,
headers: headerParams
}
});
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);
Try this. Your not include the userServices module into the userControllers module and you can omit $scope.users = Users.query(headers); part because if you put this this will call the query method.
replace controller with this code:
angular.module('userControllers', []). controller('userController', ['$scope', '$q', 'Users', '$location', function($scope, $q, Users, $location) {
$scope.viewUser = function(userId) {
$location.path('/users/'+userId);
};
$scope.createUser = function () {
$location.path('/users/create');
};
headers = {service:'json',resource:'users'};
Users.query(headers).$promise.then(function(result){
$scope.users = result;
});
}]);
and factory with this code :
angular.module('userServices', ['ngResource']).
factory('Users', ['$resource', '$q', function($resource, $q){
var factory = {
query: function (headerParams) {
return $resource('http://localhost:8080/gateway', {}, {
query: {
method: 'GET',
isArray: true,
headers: headerParams
}
})
}
}
return {
query: factory.query
}
}]);
i think this will help you.

Resources