Angular JS get object by id from $routeparams - angularjs

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

Related

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

Template Provider Doesn't Fire $Scope Logic

I'm using angular ui-router and need to show a different template for a given state based on a variable in the parent (body) scope. But when I add this $scope.data conditional it doesn't fire. I don't even get the console.log() or any url change. :(
$stateProvider.state('map1', {
url: "/content/sectionI",
templateProvider: function($scope, $http, $stateParams) {
console.log("Wowie!",$scope.data);
if($scope.data.Section_I_Part_1_Complete == "0")
{
return $http({
method: 'GET',
url: 'http://example.com/contentMore',
params: {
request: "Section_I_Part_1_Complete",
part: "1"
}
}).then(function successCallback(html) {
return html.data;
});
}
else
{
return $http({
method: 'GET',
url: 'http://example.com/contentMore',
params: {
request: "Section_I_Unlocked",
part: "map"
}
}).then(function successCallback(html) {
return html.data;
});
}
},
controller: function($scope) {
$scope.activeSection.activeSection = "notNone";
}
})
How do I do it so that I can get the template to return based on the value of a variable in the parent scope?
Just use a service to store the data and inject that service.
templateProvider: function(myDataService) {
var part = myDataService.Section_I_Part_1_Complete == "0" ? 1 : 'map';
return $http.get('http://example.com/contentMore', {
params: {
request: "Section_I_Part_1_Complete",
part: part
}
}).then(function(response) {
return response.data;
});
}

How to get the object properties using AngularJS and ASP.NET MVC

I think it is not a big problem but I can't find any solution for this. Using Angular I want to display item details from database. I have my server side code that is searching for ID and returning Json. Then in Angular controller I get the data, single record. But I can't display any informations about this. It only works when I use ng-repeat but that's not the case. There is no point to use ng-repeat when I have just one single record.
//
It shouldn't be something like this?
$scope.item = { name: 'jack', city: 'sydney' };
And in my view
{{item.name}}
But with my single record from database it's not working. Do you have any idea what is wrong here? Or maybe I'm missing something? Here is my code
ASP.NET MVC Controller:
public JsonResult GetGame(int id, string gameName)
{
var getById = GetGameById(id, gameName);
if (getById != null)
{
using (KeyGameContext dbx = new KeyGameContext())
{
dbx.Configuration.ProxyCreationEnabled = false;
var getGame = dbx.Games.Find(id);
return Json(getGame, JsonRequestBehavior.AllowGet);
}
}
else
{
return Json(null);
}
}
public Game GetGameById(int gid, string gName)
{
return db.Games.Find(gid);
}
AngularJS code:
$http({
url: '/Genre/GetGame',
params: {
id: $routeParams.id,
gameName: $routeParams.gameName
},
method: 'get'
}).then(function (data) {
$scope.getGame = data;
console.log(data);
});
And here is some informations about this record from the console
Yea this throws people off when they first start using $http. Try this
$http({
url: '/Genre/GetGame',
params: {
id: $routeParams.id,
gameName: $routeParams.gameName
},
method: 'get'
}).then(function (data) {
$scope.getGame = data.data;
console.log(data);
});
What gets passed into your "then" promise function is the response object, which contains information about the http request in addition to your data. The actual data object is stored at .data
So I usually write mine as
$http({
url: '/Genre/GetGame',
params: {
id: $routeParams.id,
gameName: $routeParams.gameName
},
method: 'get'
}).then(function (response) {
$scope.getGame = response.data;
console.log(data);
});
just replace your code
$scope.getGame = data;
to
$scope.getGame = data.data;
"Happy Coding"

Build a reusable factory 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;
});

AngularJS - transformRequest is not getting called on $resource

I am adding a pair of actions to an AngularJS resource, but when I invoke the action, my transformRequest function is not getting called:
var _resource = $resource('api/NewItem/:id',
{ id: '#id' },
{
create: {
method: 'POST',
transformRequest: function (data, headersGetter) {
var result = JSON.stringify(data.productIntro);
return result;
}
},
update: {
method: 'PUT',
transformRequest: function (data, headersGetter) {
var result = JSON.stringify(data.productIntro);
return result;
}
}
});
If I add the function globally on the app, it works:
var newItemApp = angular.module('newItemApp', ['ngResource'])
.config(function ($httpProvider) {
$httpProvider.defaults.transformRequest = function(data)
{
if (data === undefined) {
return data;
}
var result = JSON.stringify(data.productIntro);
return result;
};
});
What I need to do is remove the root element from any POST or PUT action because the default model binding in Web Api does not bind a json object when that object has a named root.
transformRequest is supported since AngularJS 1.1.2. If you use early version, you need to add it to $httpProvider.

Resources