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"
Related
Hi I am new in AngularJS and trying to fetch and show json key data separately to console window. I can able to fetch entire json data , but unable to fetch datas within a particular node. Where am I going wrong ?
Service.js
app.service("AppService", function($http) {
return {
network: [],
getAllService: function(network){
return $http({
method: 'GET',
url: 'http://99.126.4.6:3200/app/json/allDatas',
headers: {'Content-Type': 'application/json'}
})
.then(function(data) {
return data;
})
}
}
});
Controller :-
app.controller('getController', ['$scope','$http','AppService','$localStorage', function ($scope,$http,AppService,$localStorage) {
$scope.load = AppService.getAllService();
$scope.load.then(function(data) {
$scope.getAllData = data;
$scope.getId = data.ID;
$scope.getName = data.Name;
$scope.getDescription = data.Description;
console.log($scope.getId + $scope.getName + $scope.getDescription);
})
}]);
When I console getAllData I can see entire json response.But unable to fetch inner keys.
JSON response:-
Data
Array(1)
0
:
{$id: "1", ID: 1, Name: "APP", Description: "Something", Segments: Array(3)}
You are mixing the old syntax with a new one: .success vs. .then
.then() returns an Http Promise which wraps your response in an object. To pull out your data, you need to access .data first.
Fix this line from:
.then(function(data) {
return data;
})
to
.then(function(data) {
return data.data;
})
data is an array, so access it's value by index
$scope.load = AppService.getAllService();
$scope.load.then(function(data) {
angular.forEach(data, function(value) {
console.log(value.ID+" "+value.name++" "+value.escription);
});
})
I'm trying to upload an image along with other types of data using web api, angular JS .
My POST employee API controller action is :
[ResponseType(typeof(Employee))]
public async Task<IHttpActionResult> PostEmployee(Employee employee)
{
byte[] data = new byte[employee.Image.ContentLength];
employee.Image.InputStream.Read(data, 0, employee.Image.ContentLength);
employee.Picture = data;
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Employees.Add(employee);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = employee.ID }, employee);
}
The Service JavaScript is:
app.service('Service', function ($http) {
this.getEmployees = function () {
return $http.ger("/api/EmployeeApi");
}
this.post = function (Employee) {
var request = $http({
method: "post",
url: "/api/EmployeeApi/PostEmployee",
data: Employee,
headers: {
'Content-Type' : 'application/json'
}
});
return request;
};
});
The "AddEmployee " Controller which I'm using for posting employee to the server is
app.controller('AddEmployee', function ($scope, Service) {
$scope.ID = 1;
$scope.save = function () {
var Employee = {
ID: $scope.ID,
Name: $scope.Name,
Experience: $scope.Experience,
EmployerName: $scope.EmployerName,
Image:$scope.Image
};
var Post = Service.post(Employee);
Post.then(function (pl) {
alert("Student Saved Successfully.");
},
function (errorPl) {
$scope.error = 'failure loading Student', errorPl;
});
};
});
The "Image" attribute Is not being posted to the server . rather it's throwing null. Probably problem with binding . I'm not sure why the image attribute is not being bind to the model while other attributes can.
I would assume that you are using an input with a type of file in your html to get the file name. Angular does not handle the binding for these automatically, so even though the file you selected shows up in the browser, it doesn't update the model. There are a number of directives available to work around this shortcoming.
This answer covers it pretty thoroughly. ng-model for <input type="file"/>
Hey I want to change the data before sending it with ngResource (build FormData object). I do everything as in the examples that I found, however I can't make them work. Here is my code:
My controller where I set the data and try to send them:
var vm = this;
vm.application = new Application();
vm.application.title = 'Test title';
Application.save({}, vm.application, function(){
});
My service:
function application(ApiBaseUrl, $resource) {
var actions = {
'save': {
metod: 'POST',
url: ApiBaseUrl + "/applications",
headers: { 'Content-Type': false },
transformRequest: function (data) {
console.log(data); //Returns 'undefined'
return data;
}
}
};
return $resource(ApiBaseUrl + "applications/:id", {}, actions);
}
In the function transformRequest data object is always marked as 'undefined'. Am I doing something wrong? Is there a better way to edit the data before sending it?
The problem was I had
metod: 'POST'
when I should have used:
method: 'POST'
I am new at angular. I use angular.js and webapi. I have a request like below.
[HttpGet]
public RecordDTO[] GetMyFiles(UserClass usr,int uId,int fId)
{
}
my webapi call is like this. UserClass parameter is a class that has two string field(name,password). My angular code is like below.
$scope.GetMyFiles= function () {
var user = { Name:'xx',Password:'xx' };
var data = {usr:user, uId: 11, fId: 56};
$http({
url:"../api/Home/GetMyFiles",
method: 'GET',
//headers: { 'Content-Type': 'application/json' },
params: data
})
.success(function (data) {
alert("OK");
})
.error(function (data) {
alert("error");
});
};
My problem is UserClass is null. It takes uId and fId parameters, but first parameter comes null.
How can I correct this?
Thanks in advance.
As the default content-type for $http is JSON, check what your service is attending. If its JSON, you should stringify your data to pass them to your webapi :
params: JSON.stringify(data)
if you need to SEND data to the server, you should make a $http.post call. I think the problem because you are not specifiying the content-type of the header.
please try this:
$http.post('/api/Home/GetMyFiles', data , {
headers: { 'Content-Type': 'application/x-www-form-urlencoded;' }
}
).success(function(data) })
.error(function(err){});
Tell me if it works, and if you need any help let me know. Happy Coding. ;)
Change $http method from GET to POST. Also change params: data to data: data. I tried this code in my local PC and it works correctly.
Controller:
[HttpPost]
public RecordDTO[] GetMyFiles(UserClass usr, int uId, int fId )
{
}
JavaScript:
$http({
url: url,
method: 'POST',
data: data
})
.success(function (data) {
alert("OK");
})
.error(function (data) {
alert("error");
});
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;
}