$http post via an angularjs service - javascript

I use the code below. The content of dataService is all the $http possible in my application. In the controller, I consume this function. The function call a Web Api service, this one is called and return the right response. In the function customerToggleSuccess the data is undefined. I don't understand why.
(function () {
angular.module('myApp')
.factory('dataService', ['$q', '$http']);
function dataService($q, $http,) {
return {
customerToggleActive: customerToggleActive
};
function customerToggleActive(customerId, index) {
var customer = {
"id": customerId,
"index": index
};
return $http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
.then(customerToggleData)
.catch(customerToggleError)
}
function customerToggleData(response) {
return response.data;
}
function customerToggleError(response) {
}
}
}());
(function () {
angular.module('myApp')
.controller('customerController', ['$scope', 'dataService', '$http', '$log', CustomerController]);
function CustomerController($scope, dataService, $http, , $log) {
var vm = this;
vm.activeToggle = function (customerId, index) {
dataService.customerToggleActive(customerId, index)
.then(customerToggleSuccess)
.catch(customerToggleCatch)
.finally(customerToggleComplete);
function customerToggleSuccess(data) {
$log.info(data);
}
function customerToggleCatch(errorMsg) {
}
function customerToggleComplete() {
}
}
}
}());

Like this ,
(function () {
angular.module('myApp')
.factory('dataService', ['$q', '$http']);
function dataService($q, $http,) {
return {
customerToggleActive: customerToggleActive
};
function customerToggleActive(customerId, index) {
var customer = {
"id": customerId,
"index": index
};
return $http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
}
}
}());

Simply return the $http promise,
return $http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
you can access it by,
dataService.customerToggleActive(customerId, index)
.then(function (response) {
// do your stuff
})
or, you can do,
function dataService($q, $http,) {
var defer = $q.defer();
....
....
$http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
function customerToggleData(response) {
defer.resolve (response.data);
}
function customerToggleError(response) {
defer.reject(response);
}
return defer.promise;
}

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

Access database from angular component with service

I am trying to populate my combo box from the database on page load. When I debug it, debug point don't hit at adminsService.test(result) at all. Why is that? I am trying to get the data without any conditions.
angular.module('adminService', []).factory('adminService', function ($rootScope, $http) {
var modelService = function () {
}
modelService.prototype.test = function (test) {
var promise = $http(
{
method: 'POST',
url: '/Model/getTopics',
contentType: 'application/json',
data: {
test: test
}
});
return promise;
}
viewRoleModule.controller('viewRoleController', function ($scope, $routeParams, adminService) {
var self = this;
self.$onInit = function () {
self.topicRoleItems = function ()
{
adminService.test(result);
};
}
});
<div ng-repeat="item in $ctrl.topicRoleItems">
{{item.TopicName}}
</div>
Try
self.topicRoleItems = adminService.test().then(function(result){
self.topicRoleItems = result;
});
UPDATE
.factory('adminService', function ($rootScope, $http,$q) {
var modelService = [];
modelService.test = function (test) {
var deferred = $q.defer();
$http({
method: 'POST',
url: '/Model/getTopics',
contentType: 'application/json',
data: {
test: test
}
}).success(function(resp){
deferred.resolve(resp);
}).error(function(resp){
deferred.reject();
});
return deferred.promise;
}
return modelService;
})

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

Use parameters in angular factory for custom header

I'm trying to find a way to pass a parameter so I can use it in my 'endpoint' variable, as you can see in my code I have the url and in the end of it I have "/clientes", but, in my API I also have "products" and "travels", so I'm looking for a solution to use a variable so I can change the end of the url, otherwise I'll have to create another factories just to get my "products" and my "travels".
angular.module('starter.services', [])
.factory('ServiceClientes', ['$http', function ($http) {
var endpoint = 'http://api.rep.com/api/clientes';
var token = '99KI9Gj68CgCf70deM22Ka64chef2J2J0G9JkD0bDAcbFfd19MfacGf3FFm8CM1hG0eDiIk8';
var credencial = 'rm#w.com:cd8cdx5ef753a06ee79fc75dc7cfe66c';
var origem = 'mobile';
var config = {
url: endpoint,
dataType: 'json',
method: 'GET',
data: '',
headers: {
'X-API-TOKEN': token,
'X-API-CREDENCIAL': credencial,
'X-API-ORIGEM': origem,
"Content-Type": "application/json"
}
};
return {
getAll: function () {
return $http(config);
}
};
}]);
controller:
.controller('PlaylistsCtrl', function ($scope, ServiceClientes) {
ServiceClientes.getAll().success(function (data) {
$scope.playlists = data.dados;
}).error(function (error) {
console.log(error);
});
})
Then make your function injectable with a parameter:
var endpoint = 'http://api.rep.com/api/';
var config = {
dataType: 'json',
method: 'GET',
data: '',
headers: {
'X-API-TOKEN': token,
'X-API-CREDENCIAL': credencial,
'X-API-ORIGEM': origem,
"Content-Type": "application/json"
}
};
return {
getAll: function (url) {
config.url = endpoint + url;
return $http(config);
}
};
controller:
ServiceClientes.getAll("clientes").success(function (data) {

How to implement ajax call using promise with angular?

I'm trying to use angular promise using $q that is wrapped in 'service' and call it from my controller.
Here is the code:
var myController = function ($scope, myService) {
$scope.doSomething = function (c, $event) {
$event.preventDefault();
myService.method1(c).then(function (rslt) {
alert(rslt);
}, function (err) {
alert(err);
}).then(function () {
//clean up
});
};
};
var myApp = angular.module('myApp', [])
.factory('myService', function($q) {
function _method1(c) {
var dfr = $q.defer();
var dt = { sc: c };
$.ajax({
type: "POST",
url: "mypage.aspx/mymethod",
data: JSON.stringify(dt),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
dfr.resolve('actions sucess');
},
error: function (msg) {
dfr.reject(msg);
}
});
return dfr.promise;
}
return { method1: _method1 };
}).controller('myController', myController);
The problem is that ' alert(rslt);' piece of code is never executed.
Service is called and data is updated but first 'then' function is not reached on first click.
What am I doing wrong?
Any help appreciated.
I would recoomend you to use $http and $resource instead of $.ajax
Heres an example of $http
myApp.factory('MyService',
[
'$http',
'$q',
'$resource',
function (
$http,
$q,
$resource
) {
return {
doSomething : function (somedata) {
var deferred = $q.defer();
$http({ method: 'POST', url: '"mypage.aspx/mymethod"', data: somedata }).
success(function (data, status, headers, config) {
deferred.resolve(true);
}).
error(function (data, status, headers, config) {
deferred.resolve(false);
});
return deferred.promise;
}
};
}]);
Just add the dependency to $rootScope and call $rootScope.$apply() in both callbacks from $.ajax():
success: function () {
dfr.resolve('actions sucess');
$rootScope.$apply();
}, ...
But better yet, use Angular's $http service.

Categories