OK, I'm stumped. I have an angular json GET process that is pulling results in as expected but I can't seem to parse and get to individual values of the result.
Here is the string result I'm getting:
{"result":[{"sys_id":"f4425c21ec0970407e85e2a57ceff437","number":"INC0035062"}]}
And here is my code:
$http({
method:'GET',
url:$scope.url,
transformResponse: undefined}).then(function(response) {
console.log(response.data);
}).catch(function(response) {
console.error('Error', response.status, response.data);
})
.finally(function() {
console.log("All Done");
});
SO, how can I get to an individual value of a sys_id?
Thanks in advance,
DP
*******EDIT:
Sajeetharan, still having an issue. Changed code per your example:
console.log(response.data);
$scope.data = response.data.result;
console.log($scope.data);
console.log("Sys id is:"+$scope.data[0].sys_id);
Output:
{"result":[{"sys_id":"f4425c21ec0970407e85e2a57ceff437","number":"INC0035062"}]}
undefined
TypeError: Unable to get property '0' of undefined or null reference
at Anonymous function (******.EvScripts.jsdbx:59:3)
at Anonymous function (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:130:399)
at m.prototype.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:145:96)
at m.prototype.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:142:165)
at m.prototype.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:145:399)
at l (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:97:248)
at K (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:101:373)
at y.onload (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:102:397)
Error undefined undefined
If you want to access sys_id, access the 0th index of the array data,
$http.get('test.json').then(function(response){
$scope.data = response.data.result;
});
If you want to access the sys_id using expression,
In Html
<div ng-controller="ListCtrl">
<h1> Sys id is :{{data[0].sys_id}} </h1>
</div>
If you want to access the sys_id using controller,
$http.get('test.json').then(function(response){
$scope.data = response.data.result;
console.log("Sys id is:"+$scope.data[0].sys_id);
});
DEMO
This is what ended up working, via angular.fromJson:
//CALL TO REST SERVICES
//---------------------
$http({
method:'GET',
url:$scope.url,
transformResponse: undefined}).then(function(response) {
console.log(response.data);
$scope.data = angular.fromJson(response.data);
console.log($scope.data['result'][0].sys_id);
}).catch(function(response) {
console.error('Error', response.status, response.data);
})
.finally(function() {
console.log("All Done");
});
//---------------------
Related
I'm making a get request to my server, I get the response and I store the value inside a $scope.productId
userService.get(true)
.then(function(res) {
$scope.productId = res.user.productid;
}
});
then I need to use this value in another get request to the api to get the product related to this id.
apiService.get('/product/' + ???)
.then(function(response) {
console.log(response)
})
.catch(function(response) {
});
I'm new to promises, so the objective is to get the value of the first request in to the second one!
use this
userService.get(true)
.then(function(res) {
$scope.productId = res.user.productid;
apiService.get('/product/' + ???)
.then(function(response) {
console.log(response)
})
.catch(function(response) {
});
}
});
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 want to use my controller for getting images link of dog with an api but I am not able to use the result.
var images = function(breed) {
var promise = $http({
method: 'GET',
url: 'https://dog.ceo/api/breed/' + breed + '/images/random'
})
.then(function successCallback(response) {
return response.data.message;
},
function errorCallback(response) {
});
return promise;
}
console.log(images("kelpie"));
the problem is, i can't get the link in the object.
if I change response.data.message by only response.data, this is why i get
when I add console.log(response.data) before the return, this is what I get:
If I try JSON.parse(response.data), I got this:
Do you know how to do ?
Thank you for your help
What you are seeing in the console is the promise itself.
if you want to view the value (which in this case will be the url) then do it like this
console.log(images("kelpie").value);
If you want to see the response data then you need to add the console.log() in the then() callback.
Do it like this:
.then(function successCallback(response) {
console.log(response.data.message);
return response.data.message;
}
can you try one with JSON.parse(response.data) and then fetch message property from it.
You need to utilize promise here.
One way to do this is -
angular.module('demo', [])
.controller('myController', ['$scope', 'demoService', function($scope, demoService){
demoService.test().then(function(response) {
$scope.url = response;
})
}])
.factory('demoService', ['$http', '$q',
function($http, $q) {
var demoService = {};
demoService.test = function() {
var deferred = $q.defer();
$http.get('https://jsonplaceholder.typicode.com/posts/1').then(
function(response) {
response = "https://www.w3schools.com/bootstrap/paris.jpg";
deferred.resolve(response);
}, function(error) {
console.log("some error occur");
console.log(error);
deferred.reject(error);
}
)
return deferred.promise;
}
return demoService;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo" ng-controller="myController">
<img ng-src="{{url}}" />
</div>
Use promise deffer object
Refference - https://docs.angularjs.org/api/ng/service/$q
JS fiddle working code - https://jsfiddle.net/Shubhamtri/9y9ezkdt/1/
I pass two dates to the post method thro controller.The service responses back with some data based on the given input. Im using $scope.onGetData to get the data from post method, inorder to display the final result but it is not going inside the $scope.onGetData. So the question is how to fetch the response data from the service and use it inside a controller, so that I can make use of it in my view.
Controller:
$scope.computationList;
$scope.onViewLoaded = function () {
computationManagementService.getComputation($scope.onGetData);
}
$scope.onGetData = function (data,response,error) {
$scope.computationList = data;
}
$scope.calculateInput=function(start,end,htmlValidation)
{
var date={'startDate':start , 'endDate':end};
if(htmlValidation){
computationManagementService.getComputation(date,function(err,response){
console.log("pass thro controller");
});
}else{
console.log("Validation Error");
}
}
});
Service:
myApp.factory('computationManagementService', function($http, settings){
var ComputationServiceFactoryObj = {};
var _getComputation= function(date,callback){
$http({
method:'POST',
url: 'localhost:/8091/date/computation',
data: date
}).success(function(data,response,config){
callback(response);
console.log(data); // data
}).error(function (data, status, error, headers, config){
if(callback) {
callback(error);
console.log(error);
}
});
}
ComputationServiceFactoryObj.getComputation= _getComputation;
return ComputationServiceFactoryObj;
});
If you are trying to use the post method's data to the view then you can try this method And it worked for me but not sure if it is correct way of using the service.
Service:
myApp.factory('computationManagementService',
function($http, $rootScope, settings){
var ComputationServiceFactoryObj = {};
var _getComputation=function(callback){
var computationData=$rootScope.finalResult;
if(callback != null){
callback(computationData);
}
}
var _postComputation= function(date,callback){
$http({
method:'POST',
url: 'localhost:/8091/date/computation',
data: date
}).success(function(data){
callback(data);
$rootScope.finalResult=data;
console.log(data); // data
}).error(function (data, status, error, headers, config){
if(callback) {
callback(error);
console.log(error);
}
});
}
ComputationServiceFactoryObj.getComputation= _getComputation;
ComputationServiceFactoryObj.postComputation= _postComputation;
return ComputationServiceFactoryObj;
});
Some good practices:
using ngResource is always preferable to the raw $http service, except for rare cases when you need some complex configuration that ngResource can't handle (I can't think of such, though). Why? It forces you yo use promises.
return promises from your service methods instead of passing callbacks. Using callbacks will force you to call $digest on your scope so that bingings are re-evaluated, which goes against the way angular works in general and may have negative performance impact as well.
In your case I'd modify the _getComputation method to simply return a promise:
var _getComputation = function(date) {
return $http({
method:'POST',
url: 'localhost:/8091/date/computation',
data: date
});
};
In your controller:
computationManagementService.getComputation(date)
.then(function(response) {
console.log(response);
$scope.someValue = response.someValue;
}, function(error) {
console.error(error);
});
I'd rather avoid injecting $scope in controllers, and use the ngController='MyController' as 'MyCtrl' syntax instead and assign values that should be accessible by views to the controller instance.
It is better not to use .success and .error methods in your service as they are not chainable, Use .then format instead. .success/error methods are deprecated in the latest Angular version 1.6.
Here is the Deprecation notice from Angular documentaion.
In your service :
var _getComputation= function(date,callback){
return $http({
method:'POST',
url: 'localhost:/8091/date/computation',
data: date
}).success(function(data,response,config){
callback(undefined, response);
console.log(data); // data
}).error(function (data, status, error, headers, config){
if(callback) {
callback(error);
console.log(error);
}
});
}
In your Controller :
computationManagementService.getComputation(date,function(err,response){
console.log("pass thro controller");
console.log(response);
}
I am new to angular and I am trying to list my data in database .However I am gettin $scope not defined error..This is my code
productsService
.getProducts()
.success(function (data, status, headers, config) {
$scope.products = data;
console.log($scope.products);
})
.error(function (error) {
//Showing error message
$scope.status = 'Unable to retrieve product' + error.message;
});
In my product Service I have
return {
getProducts: function () {
return $http({
method: 'GET',
url: '/api/Products'
}).success(function (data) {
alert("success");
// console.log(data);
}).error(function (error) {
//Showing error message
alert("failed");
$scope.status = 'Unable to retrieve products' + error.message;
console.log($scope.status);
});
},
I am just getting failed alert. Please help!!!In backend I am able to get the data from database.
In an Angular service, you do not have access to the $scope, that is something you only have in directives and controllers. That is why you are getting an error about $scope being undefined.
Also, in your service you are returning a promise from your getProducts() method, yet you are also adding success and error handlers on to it. You should make up your mind whether you want to return the raw $http promise, or if instead you want to return a $q promise which is resolved with some transformed copy of the data returned in the $http().success() handler.
One final thing, if you are seeing the "failed" alert, that means your server is returning an error when you submit a request to /api/Products. If you go to that URL in your browser, does it work? You should look into why a basic GET request to that URL is not working.
You should not uses scope variables in your service, you service should only be used to get/update/share some data.
Here is how your service should look like
Service
return {
getProducts: function() {
return $http({
method: 'GET',
url: '/api/Products'
});
},
and in your controller for that service method you can have a .success() and .error() which you can use to set your error messages.
Controller
productsService
.getProducts()
.success(function (data, status, headers, config) {
$scope.products = data;
})
.error(function (error) {
$scope.status = 'Unable to retrieve product' + error.message;
});
Hope this helps.