I am new to AngularJS and having an strange problem, that I can't access to $scope.name. In the factory DataService I have a method getData() which uses $http.get(...).
angular.module("app", []).factory("DataService", function($q, $http) {
var service = {};
service.getData = function() {
var deferred = $q.defer();
$http.get(apiPath).success(function(data) {
deferred.resolve(data);
}).error(function(data, status) {
deferred.reject('Error: ' + status);
});
return deferred.promise;
};
return service;
}).controller("DataController", ["$scope", "DataService", function($scope, DataService) {
$scope.datas = [];
DataService.getData().then(function(data){
$scope.datas = data;
}, function(error) {
console.log(error);
});
console.log($scope.datas); // it returns []
}]);
I can't understand why it returns an empty array.
Related
LoginController.js
var MyApp = angular.module('MyApp', []);
MyApp.controller("LoginController",
["$scope", "$rootScope",
function ($scope , dataService) {
$scope.user = "sample";
$scope.checkUser = function () {
dataService.getUserData($scope.user).then(
function (results) {
$scope.userLoginInfo = results.userInfo;
},
function (results) {
$rootScope.showAlert(results, "There is a problem when trying to get user details.");
});
};
}]);
My DataService.js
MyApp.factory("dataService",
["$http", "$rootScope", "$q",
function ($http, $rootScope,$q) {
var dataService = {};
var getUserData = function (username) {
var promise = $http.get(baseUrl()+"/Controllers/UserDetails/?username=" + username)
.success(function (data, status, headers, config) {
return data;
})
.error(function (data, status, headers, config) {
return data;
});
return promise;
}
return {
getUserData: getUserData
}
}]);
i have included all .js files via bundleconfig .on calling dataService.getUserData in login controller , the described error occurs.
following is the stack trace
"TypeError: Object doesn't support property or method 'getUserData'\n at $scope.checkUser (http://localhost:58949/app/Controllers/LoginController.js:41:9)
at fn (Function code:2:195)\n at expensiveCheckFn (http://localhost:58949/Scripts/angular.js:16123:11)\n at callback (http://localhost:58949/Scripts/angular.js:26490:17)\n at Scope.prototype.$eval (http://localhost:58949/Scripts/angular.js:17913:9)\n at Scope.prototype.$apply (http://localhost:58949/Scripts/angular.js:18013:13)\n at Anonymous function (http://localhost:58949/Scripts/angular.js:26495:17)\n at n.event.dispatch (http://localhost:58949/Scripts/jquery-2.2.3.min.js:3:7481)\n at r.handle (http://localhost:58949/Scripts/jquery-2.2.3.min.js:3:5547)"
any help is greatly appreciated
You have not injected dataService so in your scenario instead of accessing "dataService" it is accesing "$rootScope"
try this :
// controller
var MyApp = angular.module('MyApp', []);
MyApp.controller("LoginController", ["$scope", "$rootScope", "dataService",
function($scope, $rootScope, dataService) {
$scope.user = "sample";
$scope.checkUser = function() {
dataService.getUserData($scope.user).then(
function(results) {
$scope.userLoginInfo = results.userInfo;
},
function(results) {
$rootScope.showAlert(results, "There is a problem when trying to get user details.");
});
};
}
]);
Also in your service
following line /Controllers/UserDetails/?username= seems to be incorrect, We pass query parameter in following way :
// "/Controllers/UserDetails?username="
// Service
MyApp.factory("dataService", ["$http", "$rootScope", "$q",
function($http, $rootScope, $q) {
var dataService = {};
var getUserData = function(username) {
var promise = $http.get(baseUrl() + "/Controllers/UserDetails?username=" + username)
.success(function(data, status, headers, config) {
return data;
})
.error(function(data, status, headers, config) {
return data;
});
return promise;
}
return {
getUserData: getUserData
}
}
]);
Inject the dataService.
MyApp.controller("LoginController",
["$scope", "$rootScope","dataService",
function ($scope ,rootScope dataService) {
. .
}
If the dataService not injected properly, hence it throws the error.
I try to use a service to get some data from server, but I had a problem: even the console log out the length when I print 'myData.length', when I try to find length of '$scope.test' controller variable it tell me that it is undefined.
What I should to do to use a $http service inside my own service?
app.controller('mainCtrl', ['$scope', 'mapServ',
function($scope, mapServ) {
$scope.test = [];
$scope.test = mapServ.test;
console.log('$scope.test = ' + $scope.test.length);
}]);
app.factory('mapServ', ['$http', function ($http) {
var path = "file path to my server data";
var out = {};
var myData = [];
out.test = $http.get(path).then(function (response) {
myData = response.data;
console.log(myData.length);
});
return out;
}]);
Take these service and controller as an example and you should follow John Papa's style guide while writing the code.
Service
(function() {
'use strict';
angular
.module('appName')
.factory('appAjaxSvc', appAjaxSvc);
appAjaxSvc.$inject = ['$http', '$q'];
/* #ngInject */
function appAjaxSvc($http, $q) {
return {
getData:function (path){
//Create a promise using promise library
var deferred = $q.defer();
$http({
method: 'GET',
url: "file path to my server data"
}).
success(function(data, status, headers,config){
deferred.resolve(data);
}).
error(function(data, status, headers,config){
deferred.reject(status);
});
return deferred.promise;
},
};
}
})();
Controller
(function() {
angular
.module('appName')
.controller('appCtrl', appCtrl);
appCtrl.$inject = ['$scope', '$stateParams', 'appAjaxSvc'];
/* #ngInject */
function appCtrl($scope, $stateParams, appAjaxSvc) {
var vm = this;
vm.title = 'appCtrl';
activate();
////////////////
function activate() {
appAjaxSvc.getData().then(function(response) {
//do something
}, function(error) {
alert(error)
});
}
}
})();
In your code you do not wait that $http has finished.
$http is an asynchronous call
You should do it like this
app.controller('mainCtrl', ['$scope', 'mapServ',
function($scope, mapServ) {
$scope.test = [];
$scope.test = mapServ.test.then(function(response) {
console.log(response.data);
}, function(error) {
//handle error
});;
}
]);
app.factory('mapServ', ['$http', function($http) {
var path = "file path to my server data";
var out = {};
var myData = [];
out.test = $http.get(path);
return out;
}]);
$http call that you are making from factory is asynchronous so it will not wait , until response come, it will move on to the next execution of the script, that is the problem only try Weedoze's asnwer, it is correct way to do this.
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 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;
}
});
Trying to return data from the factory and logging within the factory outputs the correct data, but once passed to the controller it is always undefined. If I have my factory logic inside the controller it will work fine. So it must be something simple Im missing here?
Application
var app = angular.module('app', []);
app.controller('animalController', ['$log', '$scope', 'animalResource', function($log, $scope, animalResource) {
$scope.list = function() {
$scope.list = 'List Animals';
$scope.animals = animalResource.get(); // returns undefined data
$log.info($scope.animals);
};
$scope.show = function() {};
$scope.create = function() {};
$scope.update = function() {};
$scope.destroy = function() {};
}]);
app.factory('animalResource', ['$http', '$log', function($http, $log) {
return {
get: function() {
$http({method: 'GET', url: '/clusters/xhrGetAnimals'}).
success(function(data, status, headers, config) {
//$log.info(data, status, headers, config); // return correct data
return data;
}).
error(function(data, status, headers, config) {
$log.info(data, status, headers, config);
});
},
post: function() {},
put: function() {},
delete: function() {}
};
}]);
Log Info
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
200 function (name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
} Object {method: "GET", url: "/clusters/xhrGetAnimals"}
Your get() method in service is not returning anything. The return inside the success callback only returns from that particular function.
return the $http object
Che this example that is how you use the promises and you return the factory then you access the methods injecting the service on your controller
Use dot syntax to access the function you define on the service
'use strict';
var app;
app = angular.module('app.formCreator.services', []);
app.factory('formCreatorService', [
'$http', '$q', function($http, $q) {
var apiCall, bjectArrarContainer, deferred, factory, webBaseUrl, _getFormElementsData;
factory = {};
deferred = $q.defer();
bjectArrarContainer = [];
webBaseUrl = 'https://tools.XXXX_url_XXXXX.com/XXXXXXX/';
apiCall = 'api/XXXXX_url_XXXX/1000';
_getFormElementsData = function() {
$http.get(webBaseUrl + apiCall).success(function(formElements) {
deferred.resolve(formElements);
}).error(function(err) {
deferred.reject(error);
});
return deferred.promise;
};
factory.getFormElementsData = _getFormElementsData;
return factory;
}
]);
then do it like this for example
'use strict';
var app;
app = angular.module('app.formCreator.ctrls', []);
app.controller('formCreatorController', [
'formCreatorService', '$scope', function(formCreatorService, $scope) {
$scope.formElementsData = {};
formCreatorService.getFormElementsData().then(function(response) {
return $scope.formElementsData = response;
});
}
]);