Build a reusable factory angularjs - angularjs

After I decided that $resource was not my thing, I wanted to write my own factory to play with my data. Having half written this first one, I am now trying to figure out the best way to reuse this code or my different restful objects. Should I wrap up the code below in a service where I define url and key and then create individual factories that use the service? Or do I put a factory inside a factory? I guess my end result is that I want to be able to create my factories where I define 'object' and 'key'.
app.factory('AssignmentData', function($http, apiUrl){
var object = 'assignments'
var key = 'assignmentid';
var url = apiUrl + object + '/';
var actions = {
query : function(params){
return $http({
method: 'GET',
url: url,
params: params
}).then(function(response){return response.data},
function(error){return error})
},
get : function(params){
return $http({
method: 'GET',
url: url + params[key],
params: _.omit(params, key)
}).then(function(response){return response.data},
function(error){return error})
},
save : function(object){
return true;
},
delete : function(object){
return true;
}
}
return actions;
});

I don't think I asked my question correctly. It probably had nothing to do with angularjs and was just my not knowing how to write javascript. In the end, i wrote my factory as follows which accomplished my goal (or at least I think it did)
schedApp.factory('RestData', function($http, apiUrl){
var resource = function(object){
var url = apiUrl + object +'s';
var key = object + 'id';
var id = 'id';
var actions = {
query : function(params){
return $http({
method: 'GET',
url: url,
params: params
}).then(function(response){return response.data},
function(error){return error})
},
get : function(params){
return $http({
method: 'GET',
url: url + '/' params[key],
params: _.omit(params, key)
}).then(function(response){return response.data},
function(error){return error})
},
save : function(object){
return true;
},
delete : function(object){
return true;
}
}
return actions;
}
return resource;
});

Related

Get value out of Json return

My angularJs function returns response in Json, but I am not been able to get the 'model' part out from it.
Below is my code:
this.search = function () {
var response = $http({
method: 'GET',
url: '/api/TalentPool/Search'
});
return response;
}
this.search().then(function (response) {
console.log('conscole: ' + response.data.model)
})
this.search().then(function (response) {
console.log(response.data.model)
})
And below is my mvc method:`
List<CandidateSearchViewModel> output = CRBuilderObj.ContructResultsViewModel(data);
CandidateSearch.model = output;
CandidateSearch.baseCriteria = criteria;
return Ok(CandidateSearch);
if you want to access the response of the http request then you have to resolve the promise firs. then access the model property from the response
this.search = function () {
return $http({
method: 'GET',
url: '/api/TalentPool/Search'
});
}
//resolve the promise like this
this.search().then(function(response){
console.log(response.data.model)
})

how to write different post method in angularjs?

i' using AngularJS v1.4.2. i have 2 html page , they have 2 controller.both controller have save event. how to use use http post method
first controller i'm calling post method given below
var promisePost = crudService.post(Countries);
promisePost.then(function (pl) {
alert("Sucessfully Inserted")
getCountry();
$stateParams.country = "";
}, function (err) {
alert("NOt Inserted")
});
second controller i'm calling post method given below
var promisePost = crudService.post(Levels);
promisePost.then(function (pl) {
alert("Sucessfully Inserted")
getLevel();
}, function (err) {
alert("NOt Inserted")
});
my app.js
myapp.service('crudService', function ($http, RESOURCES) {
//Create new record
this.post = function (Country) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
return request;
}
this.post = function (Level) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
return request;
}
});
but this code only take last post method.How to selecet post method properly. Anyone can helpme?
User countryPost and levelPost as follows and call those accordingly.
myapp.service('crudService', function ($http, RESOURCES) {
//Create new record
this.countryPost= function (Country) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
return request;
}
this.levelPost= function (Level) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
return request;
}
});
The best practice for using services is to return an object from it
myapp.factory('crudService', function ($http, RESOURCES) {
return {
saveCountry : function(){
return $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
},
saveLevel : function(){
return $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
}
}
});
then inject it into your controller dependencies and use it like :
crudService.saveLevel().then(function(){
//do some code here
})
Create a single post method instead and receive the url to call in it as parameter along with the data. As shown below:
this.post = function (data, remainingUrl) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + remainingUrl,
data: data
});
return request;
}

How to get the value from a resolved promise

I am new to Angular and having hard time to understand how to get the value from a resolved promise. I used $q.all([element1.$promise, e2.$promise]). I got the element1 which is a json object. For, element2 which is a scalar containing 2.0. I tried element[1] just like element[0] but it contains no property, so I don't know how to get the value. I tried .val, .data, etc. I know both the web api and angular are getting 2.0.
resolve: {
accountResource: "accountResource",
account: function(accountResource, $stateParams, $q) {
var info = accountResource.get({ accountId: $stateParams.accountId });
var currentBalance = accountResource.getCurrentBalance({ accountId: $stateParams.accountId });
return $q.all([info.$promise, currentBalance.$promise]);
}
vm.account = account[0];
vm.currentBalance = account[1];
resource function
function accountResource($resource) {
var webApiUrl = "https://localhost:44301";
return $resource(webApiUrl + '/api/account/:accountId', {}, {
get: {
method: 'GET'
},
query: {
method: 'GET',
isArray: true,
url: webApiUrl + '/api/account/search/:queryMethod/:queryString'
},
getCurrentBalance: {
method: 'GET',
url: webApiUrl + '/api/account/getcurrentbalance/:accountId'
}
});
}
You can call $q.all likes this (with dictionary instead of array):
return $q.all({info: info.$promise, currentBalance: currentBalance.$promise})
And after that get information in this way:
vm.account = account.info;
vm.currentBalance = account.currentBalance;
Try to rewrite your resource as this:
function accountResource($resource) {
var webApiUrl = "https://localhost:44301";
// Add second parameter {accountId: "#accountId"}
return $resource(webApiUrl + '/api/account/:accountId', {accountId: "#accountId"}, {
get: {
method: 'GET'
},
query: {
method: 'GET',
isArray: true,
url: webApiUrl + '/api/account/search/:queryMethod/:queryString'
},
getCurrentBalance: {
method: 'GET',
url: webApiUrl + '/api/account/getcurrentbalance/:accountId'
}
});
}
Updated
You can add transformResponse property to your getCurrentBalance function in accountResoure. And transform your value from API to json format.
getCurrentBalance: {
method: 'GET',
url: webApiUrl + '/api/account/getcurrentbalance/:accountId',
transformResponse: function (balanceFromApi) {
return { balance: balanceFromApi };
}
}
And finally you can get information, likes this:
vm.account = account.info;
vm.currentBalance = account.balance;
I tested it with $httpBackend service and everything is fine now. Hope this helps.

Angular JS get object by id from $routeparams

I'd like to retrieve an object by ID from the server using the $routeparams.
My problem is the $routeparams only has access to the "slug" of the item. Here is my current code.
Controller:
dataService.getVolunteerByID($routeParams.id)
.then(getVolunteerSuccess)
.catch(errorCallback);
function getVolunteerSuccess(data) {
$scope.volunteer = data;
}
Service:
function getVolunteerByID(volunteerID) {
return $http({
method: 'GET',
url: '/api/vol/' + volunteerID
})
.then(sendResponseData)
.catch(sendGetVolunteerError);
}
The current code is just appending the slug field instead of the id.
I was able to get it working with a forEach loop and passing the $routeparam on the response.config object. I think this is the best approach?
function getVolunteerByID(shortname) {
return $http({
method: 'GET',
url: '/api/vol',
shortname: shortname
})
.then(getVolunteerByIDSuccess)
.catch(sendGetVolunteerError);
}
function getVolunteerByIDSuccess(response) {
var log = [];
angular.forEach(response.data, function(item, key) {
if(item.shortname == response.config.shortname){
console.log(item);
this.push(item);
}
}, log);
return log;
}

How to implement passing of variable from one service method to another angular

Hi to all angular guru,
My question is how to pass the return result of one service method to the other methods. Or to make it short I have an authentication method in my service, the return object result for this is a token. The token will be used to be append in my header for the rest of my http request which reside on the same service.
E.g
my Service js
authenticatePlayer: function(postData) {
return $http({
method : 'POST',
url : api + 'auth/player',
data : postData,
headers : {'Content-Type' : 'application/json'}
})
.then(function(result) {
return result.data.token; //this is now the token
}, function (result) {
console.log(result);
});
}
within the Service js, I have other $http request such as:
getPlayerByEmail: function(email_address) {
return $http({
method : 'GET',
url : api + 'player/' + email_address,
headers : {'X-token': token}
//token here is from the authenticatePlayer method but how to get it??
})
.then(function(result) {
return result.data;
});
}
The two services methods are called in two controllers, my extended question is how to you pass the $scope from one controller to another that even when the page is refreshed the $scope value won't be destroy.
Hope it make sense.
One way to share $scope values between controllers is to create a service and inject it in any controller you want;
An example service,
angular.module('myApp', [])
.service('shareScope', function () {
return {
get: function () {
return value;
},
set: function(data) {
value = data;
}
};
});
In your controller;
function Ctrl($scope, shareScope) {
$scope.prop2 = shareScope.set('data');
$scope.both = shareScope.get();
}
Store it in a variable:
angular.module('foo').factory('someService', function() {
var token;
return {
authenticatePlayer: function(postData) {
return $http({
method : 'POST',
url : api + 'auth/player',
data : postData,
headers : {'Content-Type' : 'application/json'}
})
.then(function(result) {
token = result.data.token; //this is now the token
}, function (result) {
console.log(result);
});
},
getPlayerByEmail: function(email_address) {
return $http({
method : 'GET',
url : api + 'player/' + email_address,
headers : {'X-token': token}
})
.then(function(result) {
return result.data;
});
}
};
});

Resources