AngularJS Resource Calling Several times - angularjs

Im building a RESTFul app and using Angular for my view. I want to use resources since is the best approach to it, i follow the how-to's and made some tweaks by my own to include the header api token, the code end like this:
fcbMixApp.factory('Resources', ['$resource',
function ($resource) {
return {
seminary: function (apiToken) {
return $resource('api/seminaries/:seminary', {}, {
save: {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + apiToken
}
},
update: {
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + apiToken
}
}
});
},
attendant: function (apiToken) {
return $resource('api/attendants/:attendant', {}, {
save: {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + apiToken
}
},
update: {
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + apiToken
}
}
});
}
}
}]);
But when i call it on my controller like this:
var Seminary = Resources.seminary(User.getAuthData().access_token);
I dont expect that line to make any request to my api, but it does. My code follows:
Seminary.query(function (data) {
$scope.seminaries = data;
});
So i finally make two calls.
What im doing wrong, or what should i change.
Thanks in advance.

You should set a header with the token:
$http.defaults.headers.common["Authorization"] = 'Bearer' + apiToken;
And not in the resource itself. You should set this when the user is logged in the first time, then you will send it on all requests.
Also consider your resource looking something like this, and making a separate one for attendant:
fcbMixApp.factory('Resources', ['$resource', function ($resource) {
function setRequestData(data) {
var requestData = new Object();
requestData.seminary = data;
return angular.toJson(requestData);
}
return $resource('api/seminaries/:seminary', {}, {
save: {
method: 'POST',
headers: {"Content-Type": "application/json"},
transformRequest: setRequestData
},
update: {
method: 'PUT',
headers: {"Content-Type": "application/json"},
transformRequest: setRequestData
}
});
}]);

Here is the solution for adding your Resource Authorization headers.
AngularJS: How to send auth token with $resource requests?

Related

write angular js service to access multiple function

I am using below function to loadbenefittypes.
my get data function
$scope.loadCashBenefitTypes = function (){
$http({
method: "GET",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('JWT_TOKEN')
},
url: appConfig.apiUrl + "/benefit-types/income?income_type=Cash Benefit",
}).then(function (response) {
$scope.func1 = response.data
}, function (response) {
});
}
i am using above function to load benefit types in multiple locations in my application. therefore i need to reuse this function as a service. how i convert above function and how i assign it to different drop down models
To re-factor the code to a service, return the $http promise:
app.service("myService", function($http, appConfig) {
this.getCashBenefitTypes = function (){
return $http({
method: "GET",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('JWT_TOKEN')
},
params: { income_type: 'Cash Benefit' },
url: appConfig.apiUrl + "/benefit-types/income",
}).then(function (response) {
return response.data;
});
}
});
Then inject that service in the controllers:
app.controller("app", function($scope, myService) {
myService.getCashBenefitTypes()
.then(function(data) {
$scope.types = data;
}).catch(response) {
console.log("ERROR", response);
});
});
For more information, see
AngularJS Developer Guide - Creating Services

Error Using Method Post AngularJs

can someone fix it, when i using postman my restfull is good but not from my client side
var req = {
method: 'POST',
url: 'http://localhost:8098/getfiles',
headers: {
'Content-Type': 'multipart/form-data',
},
data: { 'selectedFiles': 'D:\\quadtech\\Intellegent\\AppSpringBoot\\input\\bismillah.txt' }
}
return $http(req).then(function(response){console.log(response); return response;}, function(){});
error in my console is
POST http://localhost:8098/getfiles 500 ()
this is request from postman
Send using formData instead of data:
var req = {
method: 'POST',
url: 'http://localhost:8098/getfiles',
headers: {
'Content-Type': 'multipart/form-data',
},
formData: {
'selectedFiles': fs.createReadStream('D:\\quadtech\\Intellegent\\AppSpringBoot\\input\\bismillah.txt') }
}
return $http(req).then(function(response){console.log(response); return response;}, function(){});
see the docs: https://github.com/request/request#forms

angularjs how can pass multipul parameter to api

How can I pass mutipul parameters from angularjs -to WebAPi My Api as its Required two parameters
public IHttpActionResult GetData(int pagesize,int Totalpages){---}
angularctrls.js
function GetData() {
var PageDetails={
'currentpage': $scope.currentPage,
'pagesize':$scope.pagesize
}
HomeFactory.GetDat(PageDetails).then(function () {
})
}
Factory.js
EmployeeServiceFactory.GetDat = function (PageDetails) {
return $http({
url:WebAPi+'Home/GetData/',
method: 'GET',
data: PageDetails,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
}
Getting Error as
Failed to load http://localhost:3084/Home/GetData/%7B%22currentpage%22:1,%22pagesize%22:5%7D: No 'Access-Control-Allow-Origin' header is present on the requested resource
try params instead of data like below:
EmployeeServiceFactory.GetDat = function (PageDetails) {
return $http({
url:WebAPi+'Home/GetData/',
method: 'GET',
params: PageDetails,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
}
I think you can put data as an object.
EmployeeServiceFactory.GetDat = function (PageDetails) {
return $http({
url:WebAPi+'Home/GetData/'+PageDetails,
method: 'GET',
data: {page_details:
PageDetails, foo: 'bar'}, headers: { 'Content-Type': 'application/x-www-form-urlencoded'
}
})
}

HttpResponseMessage from WebAPI from angular http post call

I have a UI project , which is an Angular JS project and Web API project and i am new to Angular. I am calling a login method of API controller which does the DB check and its sending OK message. But its going to error part of Angular http promise call. What can be the possible reasons? This is the API Call
function AutenticateUser(input) {
var deferred = $q.defer();
$http({
method: 'POST',
data: input,
url: config.serviceUrl + config.loginUrl,
transformRequest: function (input) {
var str = [];
for (var p in input)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(input[p]));
return str.join("&");
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
}).then(function (result) {
userInfo = {
accessToken: result.data.access_token,
userName: input.username
};
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
Does the accept header has to do anything with it?

How to pass headers on the fly to $resource for angularjs

Right now, the only way that I know for setting tokens in headers dynamically for an angularjs call is via $http like so:
return $http.get({
url: 'https://my.backend.com/api/jokes',
params: {
'jokeId': '5',
},
headers: {
'Authorization': 'Bearer '+ $scope.myOAuthToken
}
});
But I want to figure out how to pass this via $resource, here's some pseudo-code that doesn't work:
...
.factory('myFactory',
['$resource',
function($resource){
return {
jokes: $resource('https://my.backend.com/api/jokes', null, {
query: {
method: 'GET'
}
})
};
}
]
);
...
return myFactory.jokes.query({
'jokeId': '5',
'headers': {
'Authorization': 'Bearer '+ $scope.myOAuthToken
}
});
How can I pass headers on the fly to $resource for angularjs?
I don't think this can be done the way you are trying, as the config object is not available on action method. But the action config method has it. So what you can do is, rather than returning resource directly, create a function that takes a parameter the authorization token and then construct the resource and return.
return {
jokes: function (token) {
return $resource('https://my.backend.com/api/jokes', null, {
query: {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token
}
}
})
}
};
Then call the service function as:
myFactory.jokes($scope.myOAuthToken).query({'jokeId': '5'});

Resources