Fetching particular json key from controller AngularJS 1 - angularjs

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

Related

how to pass http data from service to controller in angularjs

var locationListCtrl=function($scope, loc8rData){
$scope.message = "Searching for nearby places";
loc8rData
.success(function(data){$scope.message = data.length > 0 ? "" : "No locations Found";
$scope.data = { locations: data };
})
.error(function(e){
$scope.message = "Sorry, Something has gone wrong";
console.log(e);
});
};
var loc8rData = function ($http){
return $http.get('/api/locations?lng=33.7741195&lat=-13.9626121&maxDistance=20');
};
Some points:
take into consideration, when you received one response from $http it's the common response (with status, headers, etc). So, if you want to access your data you will have to do: response.data
Usually, when you have a service, you define multiple endpoints. So, you can return an object with multiple requests.
Check this little sample working: https://plnkr.co/edit/FNxEeVZti6D1wmLe
.service('PokeApi', function($http) {
return ({
getPokemon: function (name) {
return $http({
method: 'GET',
url: 'https://pokeapi.co/api/v2/pokemon/' + name,
headers: { 'Content-Type': 'application/json' }
});
}
})
})
And the controller is as simple as:
.controller('MainCtrl', function($scope, PokeApi) {
$scope.name = 'Plunker';
PokeApi.getPokemon('pikachu').then(function (response) {
$scope.pokemon = response.data;
});
});

AngularJS with $q data lost when chaining promises

In the following code I want to execute a series of $http requests that modify a list. When all the responses are received, I want to process the list and remove part of the content.
The problem is that when I print the list after $q.all, the Chrome console shows a length of 3, but when I expand it to read the content only 2 elements are shown. On JSFiddle I have no issues, though.
var app = angular.module('MyApp',[]);
app.controller('MyController',['$scope','$q',"$http", function($scope,$q,$http){
var loopPromises = [];
var workorders = null;
$scope.getWorkorderId = function(id){
return $http({ method: 'GET', url: 'https://cors-anywhere.herokuapp.com/https://blk.clojure.xyz/interdiv/api/v1/service/' + id })
.then(function success(response) {
return response.data;
}, function error(response) {
console.log(response);
});
}
$http({ method: 'GET', url: 'https://cors-anywhere.herokuapp.com/https://blk.clojure.xyz/interdiv/api/v1/workorder' })
.then(function success(response) {
workorders = response.data;
}, function error(response) {
console.log(response);
})
.then(function() {
if (workorders == null) {
return;
}
angular.forEach(workorders, function(value, index, obj) {
var deferred = $q.defer();
loopPromises.push(deferred.promise);
var waitResponse = $scope.getWorkorderId(value.id);
waitResponse
.then(function(res) {
obj[index].services = res;
deferred.resolve();
})
});
$q.all(loopPromises)
.then(function() {
// Should contain 3 elements, only 2 are shown
console.log(workorders);
});
});
}]);
see better in the screenshots. Console Requests
The problem was in the second part of the code not copied in the question: I was using .splice() inside angular.forEach() which changes the indices of the elements within the array.

Ionic angular service only return data after controller call

I have a service that do two $http.get to get data from two source and concat into an array and return it to controller.
angular.module('starter.controllers').factory('GetDataList', function ($http) {
var arrDataList = [];
var postData1 = {
"param": "1"
};
var postData2 = {
"param": "2"
};
$http({
method: 'GET',
url: 'https://localhost/search',
data: postData1
})
.then(function (items) {
debugger
arrDataList = arrDataList.concat(items.data.list);
});
$http({
method: 'GET',
url: 'https://localhost/locate',
data: postData2
})
.then(function (items) {
debugger
arrDataList = arrDataList.concat(items.data.list);
});
return {
getAPIData: function () {
debugger
return arrDataList;
}
};
});
In my controller, I call it like this:
$scope.GetList = function () {
debugger
$scope.item = GetDataList.getAPIData();
$scope.$broadcast('scroll.infiniteScrollComplete');
}
When I use the debugger in console, I notice that
1) getAPIData() will be called first but it has data in it
2) Next debugger triggered at the controller which GetDataList.getAPIData(); does not return any data for $scope.Item
3) The last debugger reach $http call which return the data correctly as I observed in the console. But it never reach the controller side afterwards so no data is being displayed in the mobile app
I read about the natural behavior of angular async call so this seems to be normal. But in my case, what should I do to ensure that the data could reach the controller?
Many thanks
To achieve that without loosing performance, you should use $q.all(), so it will keep your request async and it will return the data once all the promises are resolved. Don't try a synchronic approach because that will reduce your performance.
You can use it like this:
Your factory:
app.factory('GetDataList', function($q, $http) {
var promises = [];
var arrDataList = [];
var requests = [{
url: 'https://localhost/search',
postData: {
"param": "1"
}
}, {
url: 'https://localhost/locate',
postData: {
"param": "2"
}
}];
angular.forEach(requests, function(req) {
executeRequest(req);
})
function resolveData(data) {
debugger
if (arrDataList.length === 0) {
arrDataList = data.data;
} else {
arrDataList = arrDataList.concat(data.data);
}
}
function executeRequest(req) {
var promise = $http({
url: req.url,
method: 'GET',
data: req.postData
})
.then(resolveData);
promises.push(promise)
}
return {
getAPIData: function() {
debugger
return $q.all(promises).then(function() {
return arrDataList
});
}
}
});
And your controller:
$scope.GetList = function() {
debugger
GetDataList.getAPIData().then(function(item) {
$scope.item = item
});
$scope.$broadcast('scroll.infiniteScrollComplete');
}
What we are doing here is executing each request inside the requests array (using its url and postData) asynchronously and saving the promises inside an array. When getApiData is called, it returns a function that will be called after $q.all(promises), that means it will return the data after all those promises are finished (the promises ask if the arrDataList is empty and concats the new data if it's not).
This way you get to keep your async calls! And inside the controller you receive a promise instead of the data itself.
You should make it to be synchronized as in the below
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,serviceDemo) {
$scope.name = 'World';
});
app.factory('serviceDemo', function ($http) {
var arrDataList = [];
var postData1 = []; var postData2 =[]
var firstMethod=function(){
$http({
method: 'GET',
url: 'a.json'
})
.then(function (response) {
console.log(response);
postData1=response.data;
arrDataList.push(postData1);
// console.log(postData1);
secondMethod(); //put the second method call here
});
}
var secondMethod=function(){
$http({
method: 'GET',
url: 'b.json'
})
.then(function (response) {
postData2=response.data;
arrDataList.push(postData2);
console.log(arrDataList);
});
}
var getAPIData= function () {
firstMethod();
return arrDataList;
}
return {
getAPIData: getAPIData
};
});
Modification Made:
You need to call the second method inside the success block of your first method. By this way your first method gets executed, when the result is fetched your second method gets executed and then only control will come out of the first method block.
LIVE DEMO

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"

Extract returning data from an angular promise

Greetings to everyone.
I'm trying to get data returned from an $http on angular. I created a factory:
.factory('MyFactory', function($http, SKURL) {
return {
all: function(my_data) {
return $http({
method: 'POST',
url: SKURL.url,
data: "data=" + my_data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
}
})
Then, in the controller, I write:
var n = MyFactory.all(my_data);
When I see console.log(n), I see the returned object is a promise: Promise {$$state: Object}. I see the data when I expand the object. But, when I try get n.$$state.value.data I get undefined. How can I get the data returned for the $http ?
In you controller, try the following instead:
var n;
MyFactory.all(my_data).then(function(response) {
n = response.data;
console.log(n); // this should print your data;
// do something with 'n' here.
}, function(err) {
// handle possible errors that occur when making the request.
});

Resources