AngularJS convert $http to $resource - angularjs

I am new to angular so this is probably a simple question.
I have a service that looks like this:
.factory('MoltinApi', ['$resource', '$http', 'moltin_options', 'moltin_auth', function ($resource, $http, options, authData) {
var api = $resource(options.url + options.version + '/:path', {
path: '#path'
});
var authenticate = function () {
if (!options.publicKey)
return;
var request = {
method: 'POST',
url: options.url + 'oauth/access_token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: "grant_type=implicit&client_id=" + options.publicKey
};
$http(request).success(function (response) {
authData = response;
console.log(response);
});
};
authenticate();
return api;
}])
as you can see, there is an authenticate method which is called when the class is instantiated. What I would like to do, is convert it from being an $http call and use $resource instead (because I am returning a $resource and it just seems messy to be using both $http and $resource).
Does anyone know how I can do that?

Related

return a value from $get factory method when calling service from controller in AngularJs

Im trying to call service from controller which gives me below error..
Provider 'loginService' must return a value from $get factory method.
Below is my code.What is that im doing wrong.
CONTROLLLER CODE
app.controller('loginController', ['$scope', '$http', 'loginService', function ($scope, $http, loginService) {
$scope.checkdata = function () {
var userName = $scope.username;
var password = $scope.password;
//Call the login service
loginService.validateUser(userName, password);
alert(response.data);
}
}])
Service code
app.factory('loginService', function ($http) {
this.validateUser = function (userName, password) {
var userData = new Object();
userData.userName = userName;//Data.username;
userData.password = password;//Data.password;
return $http({
url: "http://localhost:53181/api/User",
dataType: 'json',
method: 'POST',
data: userData,
headers: {
"Content-Type": "application/json"
}
}).then(function (response) {
alert(response);
if (response.data && response.data.data && response.data.data.length == 1)
return response.data.data[0];
});
}
});
Create service funtcion like this:
yourAPICallingFuntion: function() {
var url = "your url";
var deferred = $q.defer();
$http.get(url, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(function(data) {
deferred.resolve(data.data);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
In Controller Call like this:
loginService.yourAPICallingFuntion().then(function(data){
//Now this will give you response in form of data
//you can this data according to your requirement
});
factory service is expected to return a value from factory function. It doesn't have this context (it's either window or undefined).
If you want to use this like this.validateUser = ..., use service service instead.

angular $resource send request with DELETE method and request body get 415 error

I send a delete quest via angular $resource, however it always get 415 error and the request body was turn to string looks like a get request.
'use strict';
(function(angular, window){
var authsys = angular.module('authsysApp');
authsys.factory('$_privilege', ['$resource', '$q', '$notify', function($resource, $q, $notify){
var resource = {
//删除权限
batchRemovePrivilege: $resource(window.ctxPath + '/rolepri/batchDeletePrivilegeFromRole', {}, {delete:{method: 'DELETE'}})
};
return {
batchRemovePrivilege: batchRemovePrivilege
};
function batchRemovePrivilege(params){
var q = resource.batchRemovePrivilege.delete(params).$promise;
return q.then(function(){
return true;
});
}
}]);
})(angular, window);
Try to add a header to your request:
var resource = {
//删除权限
batchRemovePrivilege: function(params){
return $http({
method: 'DELETE',
url: window.ctxPath + '/rolepri/batchDeletePrivilegeFromRole',
data: params,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
};
execute:
var q = resource.batchRemovePrivilege(params).$promise;

Web Api & Angular js

I am facing a problem while calling a service using $http.
I am opening an .aspx page using iframe and on the page load i want to call a service which i written in the controller but $http is taking full path of the page and then path of the web api service as shown below.
http://localhost:50802/TST00111CFG/app/DispatchNotify/api/DispatchNotifyService/GetWorkOrders
and i want in the below manner
http://localhost:50802/TST00111CFG/api/DispatchNotifyService/GetWorkOrders
My controller code is like this
dbSrvc.getDatFromService('api/DispatchNotifyService/GetWorkOrders', $scope.workOrder).then(function (result) {
debugger;
});
Please help me out in this.
dnApp.service('dbSrvc', ["$http", "$q", function ($http, $q) {
var getDataService = function (url, val) {
debugger;
var deferObj = $q.defer();
$http({
url: url,
method: 'Get',
data: val
}).then(function (data) {
deferObj.resolve(data);
});
return deferObj.promise;
};
var postDataService = function (url, val) {
debugger;
var deferObj = $q.defer();
$http({
url: url,
method: 'Post',
data: val
}).then(function (data) {
deferObj.resolve(data);
});
return deferObj.promise;
};
return {
getDatFromService: getDataService, //To Get Data From Service
postDataToService: postDataService //To Send Data and Retrieve from Service
}

Sending POST request with form-urlencoded parameters in AngularJS using ngResource

I am trying to do a POST request with ngResources in AngularJS, I want to send my parameters in url and I have changed headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, in $save method in ngResources. The request goes out with the correct content type, but the data goes as a JSON. Is there any standard way to overcome this problem?
The factory
.factory('Token', ['$resource', function ($resource) {
return $resource('http://myProject/token/ ', { }, {
save: {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
});
}])
The calling function
.service('tokenService', ['$http', 'Token',
function ($http, Token) {
this.getToken = function () {
var t = new Token()
t.name = 'myName';
t.password = '78457'
return t.$save();
};
}])

$http POST & $http GET in 1 service

I want create 1 service where i can POST the data and on success i can again GET the data and update the $scope.variable??
How to do that?
I've tried this way:
angular.module('mvc')
.factory('ajaxService', function($http) {
return {
getAjaxData: function(response) {
$http.get(url).success(response);
return response;
},
postAjaxdata: function(postData){
$http({
method: "post",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: url,
data: data
})
.success(function(response){
ajaxService.getAjaxData(function(response) {
$scope.foo = response;
});
});
}
}
});
Capture this in postAjaxdata() to be used in the success callback to call getAjaxData().
You don't have access to the scope inside of the service (nor do you want to access it from a service). The Angular convention is to return a promise to the controller so that it can apply the response value to the scope when the promise is resolved. You can also do this using callbacks (to be consistent with the code that was posted). Here, I've added a callback to postAjaxdata()...
angular.module('mvc')
.factory('ajaxService', function($http) {
return {
getAjaxData: function(successCallback) {
$http.get(url).success(successCallback);
return successCallback;
},
postAjaxdata: function(postData, successCallback){
var that = this;
$http({
method: "post",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: url,
data: data
})
.success(function(){
that.getAjaxData(successCallback);
});
}
}
});
The controller should look something like this...
function controller ($scope, ajaxService) {
// ...
ajaxService.postAjaxdata(postData, function (response) {
$scope.foo = response;
});
}
The main issue is that you can't set scope variables in the way you attempted to from the service.
You could instead use the $q service to return a promise which, when resolved, is set to your $scope.foo variable:
.factory('ajaxService', function($http, $q) {
var ajaxService = {
getAjaxData: function() {
return $http.get(url);
},
postAjaxdata: function(postData){
var deferred = $q.defer();
$http({
method: "post",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: url,
data: postData
})
.success(function(){
deferred.resolve(ajaxService.getAjaxData());
});
return deferred.promise;
}
};
return ajaxService;
});
You'll also notice that I set the body of your factory to a named variable, which you can then use to call functions internally (as you did with ajaxService.getAjaxData()) before returning.
Then, in your controller, you could set your scope variable like this:
.controller('MyController', function($scope, ajaxService){
ajaxService.postAjaxdata().then(function(results){
$scope.foo = results.data;
})
})
Working Plunker
Note: my answer is not entirely dissimilar to Anthony Chu's. I noticed that he posted his just before mine, but I went ahead anyway since mine takes a slightly different approach, utilizing promises instead of callbacks.

Resources