Angular factory success and error callback - javascript

I've set a factory with callback for success and error. However when I use it in the controller I need to alway define both success and error functions if I don't define a error callback function, it won't work.
Is there anyways that could make error callback optional when it needs to be use.
Controller
$scope.saveUsername = function(){
atFactory.saveUsername($scope, function(){
// this is success
}, function(){
// this is error
});
}
Factory
at.factory('atFactory', ['$http' , function ( $http ){
var factory = {};
factory.saveUsername = function($scope,callback){
$scope.url = '/member/username';
$scope.post_data = {
username : $scope.username
};
factory.doPostHttpRequest($scope).success(callback).error(callback);
}
factory.doPostHttpRequest = function($scope){
return $http({
url : $scope.url,
method: 'POST',
data: $scope.post_data
})
}
return factory;
}]);

My suggestion to you is to return the $http promise back to the controller, then you can call the success() in your controller (and optionally error()).
So in your factory:
factory.saveUsername = function($scope){
$scope.url = '/member/username';
$scope.post_data = {
username : $scope.username
};
return factory.doPostHttpRequest($scope);
}
factory.doPostHttpRequest = function($scope){
return $http({
url : $scope.url,
method: 'POST',
data: $scope.post_data
})
}
Then in your controller, you can do:
atFactory.saveUsername($scope)
.success(function(response) {
// success callback (optional)
})
.error(function(error) {
// error callback (optional)
});

you can use :
at.factory('atFactory', ['$http' , function ( $http ){
var factory = {};
factory.saveUsername = function($scope,successCallBack, errorCallBack){
$scope.url = '/member/username';
$scope.post_data = {
username : $scope.username
};
return factory.doPostHttpRequest($scope).success(function(){
if(successCallBack){
successCallBack();
}
}).error(function(){
if(errorCallBack){
errorCallBack();
}
});
}
factory.doPostHttpRequest = function($scope){
return $http({
url : $scope.url,
method: 'POST',
data: $scope.post_data
})
}
return factory;
}]);

Related

Angular JS Service Creation Error

I have created this service.
and using **enrollments.getProperty();**this statement to call this service but it's not working I'm new to angular-JS please let me know where I making the mistake.
var helloAjaxApp = angular.module("myApp", []);
helloAjaxApp.service('enrollments', [ '$scope', '$http', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
var enrollments = null;
enrollment();
$scope.enrollment=function () {
$http({
url : 'enrollments',
method : "GET"
}).then(function(response) {
enrollments = response.data;
alert("enrollments");
});
};
return {
getProperty: function () {
return enrollments;
},
setProperty: function(value) {
enrollments = value;
}
};
}]);
use angular.module()
(function () {
'use strict';
angular.module("helloAjaxApp")
.service('enrollments', ['$scope', '$http', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
var enrollments = null;
enrollment();
$scope.enrollment = function () {
$http({
url: 'enrollments',
method: "GET"
}).then(function (response) {
enrollments = response.data;
alert("enrollments");
});
};
return {
getProperty: function () {
return enrollments;
},
setProperty: function (value) {
enrollments = value;
}
};
}]);
});
Angular has 2 ways of defining a service: service and factory.
here you can see the difference: https://blog.thoughtram.io/angular/2015/07/07/service-vs-factory-once-and-for-all.html
The basic difference is that service is like a constructor, so you don't return an object from it but define the properties using this keyword:
this.getProperty = function () {
return enrollments;
}
When using the factory method, is expects an object to be returned with the exposed properties/functions.
You are using the factory syntax, so just change the definition to use factory:
helloAjaxApp.factory('enrollments', [ '$scope', '$http', function ($scope, $http)
You should go for a proper service structure like so:
var helloAjaxApp = angular.module("myApp", []);
function EnrollmentService($scope, $http) {
let _this = this;
this.enrollments = null;
this.getEnrollments = function() {
return $http({
url: 'enrollments',
method: 'GET'
}).then(function(response) {
_this.enrollments = response.data;
return _this.enrollments;
})
};
this.setEnrollments = function(enrollments) {
_this.enrollments = enrollments;
}
}
helloAjaxApp.service('enrollments', ['$scope', '$http', EnrollmentService]);
Then, use the service anywhere else:
enrollmentService
.getEnrollments()
.then(function(enrollments) {
// You can use the data here.
console.log(enrollments);
});
The controller code
LoginService is service name you have to pass as a parameter to controller
var loginModule = angular.module('LoginModule',[]);
loginModule.controller('logincontroller', ['$rootScope','$scope','$http','$window','$cookieStore',
'LoginService',logincontrollerFun ]);
function logincontrollerFun($rootScope, $scope, $http, $window,$cookieStore, LoginService,RememberService) {
$scope.loginTest = function() {
LoginService.UserStatus($scope, function(resp) {
console.log("response of login controller ::: ", resp);
///write ur code
});
}
}
service code
var loginModule = angular.module('LoginModule')
loginModule.factory("LoginService",[ '$http', LoginServiceFun ])
function LoginServiceFun($http) {
function UserStatus($scope,callback){
var targetRequestPath='./url';
var targetRequestParamsREQ={'email':$scope.email,'password':$scope.passWord};
return $http({
method: 'POST',
url: targetRequestPath,
headers: {'Content-Type': 'application/json'},
data: targetRequestParamsREQ
}).then(function (response){
console.log('Response Data : ', response.data);
callback( response.data );
})
}
return {
UserStatus:UserStatus
}
}

service does not return data to controller in angular

Here is my service:
app.service('trackService', ['$http', function($http) {
var data;
this.topTracks = function(limit) {
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json', limit: limit}
}).success(function(result) {
this.data = result.tracks; console.log(this.data); return this.data;
});
}
}]);
and controller -
app.controller('artistSongsCtrl', ['$scope', 'trackService', function($scope, trackService) {
$scope.data = trackService.topTracks(10);
//console.log($scope.data);
}]);
how to send data to the controlller using a $http service inside a custom service?
Several problems are $http is asynchronous and your service method topTracks() doesn't return anything. Also you can't return inside success, there is nowhere to return to ... use then() instead
You need to return the promise from service and set the scope in a promise callback in controller
app.service('trackService', ['$http',
function($http) {
var data;
var self = this;
this.topTracks = function(limit) {
return $http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
params: {
api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf',
format: 'json',
limit: limit
}
}).then(function(result) {
self.data = result.data.tracks;
console.log(self.data);
return self.data;
});
}
}
]);
app.controller('artistSongsCtrl', ['$scope', 'trackService',
function($scope, trackService) {
trackService.topTracks(10).then(function(data) {
$scope.data = data;
//console.log($scope.data);
});
}
]);
Inside your service you are making an asynchronous GET request. In order to let the controller catch that response, you need to return a promise. Here's an example using $q:
app.service('trackService', ['$http', '$q', function($http, $q) {
var data;
this.topTracks = function(limit) {
var d = $q.defer();
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json', limit: limit}
}).success(function(result) {
this.data = result.tracks;
console.log(this.data);
d.resolve(this.data);
});
return d.promise;
}
}]);

AngularJS: Get $http response from function in module

how do i get the response from $http in from a function in a module?
Angular module:
// module customServices
var customServices = angular.module("customServices", []);
// object for response
httpResponse = {content:null};
// function sendRequest
function sendRequest(param)
{
// inject $http
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
// set header
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$http({
// config
method: 'POST',
url: 'response.php',
data: $.param(param),
// success
}).success(function (response, status, headers, config) {
httpResponse.content = response;
// error
}).error(function (response, status, headers, config) {
console.warn("error");
});
}
// factory - moduleService
customServices.factory("moduleService", function () {
return {
// function - members
members: function(param)
{
switch(param.fc)
{
// getAll
case 'getAll':
sendRequest({
service :'members',
fc : param.fc,
id : param.id
});
return httpResponse;
}
},
};
});
Controller:
myApp.controller('main', ['$scope', '$http', 'moduleService', function($scope, $http, moduleService){
$scope.handleClick = function () {
var ReturnValue = moduleService.members({
fc:'getAll',
id:'123',
});
console.log(ReturnValue);
};
}]);
the object is on the first click empty and on the second click its content is the $http response.
but i want that the controller knows when the $http response is available.
i tried to use $broadcast and $on, but it seems to be impossible to use $rootScope in my function "sendRequest".
A couple of things:
Why are you defining the httpResponse instead of just returning something from the sendRequest function?
Why are you defining a function outside angular instead of putting it as a service or factory?
You should create a service with the sendRequest method inside like this:
customServices.factory("yourNameHere", function($http, $q) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
return {
sendRequest: function sendRequest(param) {
return $http({
method: 'POST',
url: 'response.php',
data: $.param(param),
})
.then(function(response) {
return response;
})
.catch(function(response) {
console.warn("error");
return $q.reject(response);
});
}
};
});
Then in the other service:
customServices.factory("moduleService", function (yourNameHere) {
return {
// function - members
members: function(param)
{
switch(param.fc)
{
// getAll
case 'getAll':
return yourNameHere.sendRequest({
service :'members',
fc : param.fc,
id : param.id
});
}
},
};
});
Now the result will be a promise, so you can consume the data like this:
moduleService.members({
fc:'getAll',
id:'123',
})
.then(function(result) {
console.log(result);
});

sharing $scope between 2 function within one controller

app.controller('AppCtrl', ['$scope', '$http','$stateParams','getTopicContent', function($scope,$http,$stateParams,getTopicContent){
$scope.ionLoader = true;
getTopicContent.request($stateParams.topicId).then(function(response){
$scope.threadContent = response.data;
}).finally(function(){
$scope.ionLoader = false;
});
$scope.loadPages = function ($scope) {
if(totalPages > 1){
$http({
url: "http://someurl.php",
method: "GET",
params: {topicId: $stateParams.topicId,page : 2}
}).success(function(data){
$scope.threadContent.push(data);
});
}
}
}]);
I got an error saying push of undefined. loadPages only fire when the user scrolled to the bottom of the page so I don't think it's an async issue, probably $scope problem? getTopicContent is my service.
You can use promise for async working and remove parameter $scope in loadPages like that:
app.controller('AppCtrl', ['$scope', '$http','$stateParams','getTopicContent', function($scope,$http,$stateParams,getTopicContent){
$scope.ionLoader = true;
var promise = getTopicContent.request($stateParams.topicId).then(function(response){
$scope.threadContent = response.data;
}).finally(function(){
$scope.ionLoader = false;
});
$scope.loadPages = function() {
if(totalPages > 1){
$http({
url: "http://someurl.php",
method: "GET",
params: {topicId: $stateParams.topicId,page : 2}
}).success(function(data){
promise.then(function(none) {
$scope.threadContent.push(data);
});
});
}
}
}]);

How to take the resposne from one ng controller to another ng cntroller

I am a newbie to ng. Here, I have a scenario where I need to take the response received from success to another controller. I have tried the below code but I am not able to achieve my target.
CODE:
$scope.received = function(){
$http({
url : "/generic/getdata",
method : 'GET',
}).success(function(data) {
//The data received here I need t take to mydataController
$location.path('/success');
})
when('/success', {
templateUrl: 'ngtemplates/success/success.html',
controller: 'mydataController'
}).
app.controller('mydataController',
[ '$scope', '$http',function($scope, $http,$location) {
//I want the success data here in some function
}]);
Please, help me
you can use a service for your purpose.
SERVICE :
myApp.factory('dataService', function() {
var _data;
this.setData = function(someData) {
_data = someData; // better use angular.copy() function
}
return {
data : _data;
}
});
HTTP CALL :
$http({
url : "/generic/getdata",
method : 'GET',
}).success(function(data) {
//The data received here I need t take to mydataController
// before using dataService, make sure you inject it to the controller
dataService.setData(data);
$location.path('/success');
});
CONTROLLER
app.controller('mydataController',
[ '$scope', '$http',function($scope, $http,$location, dataService) {
//I want the success data here in some function
var someData = dataService.data;
}]);
You have 2 solutions. you can make a Service or use events.
$http({
url : "/generic/getdata",
method : 'GET',
}).success(function(data) {
$rootScope.$broadcast('dataReceived', data);
$location.path('/success');
});
In mydataController:
$rootScope.$on('dataReceived', function(e, data) {
// do something with the data
}
Or you can make a service to share the data between the two.
angular.module('demo').service('myDataService', function() {
this.data = null;
this.setData = function(data) {
this.data = data;
}
});
in the controller:
$http({
url : "/generic/getdata",
method : 'GET',
}).success(function(data) {
myDataService.setData(data);
$location.path('/success');
});
In mydataController:
$scope.something = myDataService.data;

Categories