In the promise then function when you receive the data object it is wrapped with another data object like
data = Object {data: Object, status: 200, config: Object, statusText: "OK"}
How to avoid this. you need to access your variables like data.data.myVar
var test123 = $scope.test();
test123.then(function(data){
console.log(data);
// why you need to access your data in "data.data.myValue"
},function(data){
});
$scope.test = function(){
var promise = $http(
{
method: 'GET',
dataType: "jsonp",
url: 'json/requestKey.json'
}
)
.success(function(data) {
return data;
})
.error(function(data){
//return data;
});
return promise;
};
Just return the data part from your "service". And you can ditch the redundant promise since $http is already a promise.
$scope.test().then(function(data) {
console.log(data);
});
$scope.test = function() {
return $http('json/requestKey.json').then(function(response) {
return response.data;
});
};
Well this is be resolved two ways
Try returning the resulting object instead of wrapping it around another object and then returning that to the client on the server side.
In the success() callback of your $http, return data.data instead of just return data, so that in your then() function you will get the internal object.
When you are returning, HttpResponseMessage, REST api response data in this format,
Object {data: Object, status: 200, config: Object, statusText: "OK"}
To parse in ajax success call back,
$http.get(urlBase + '/get/' + id).then(function (response) {
var yourData = response['data'];
var yourStatusCode = response['status'];
var yourStatusText = response['statusText'];
//assign data to any other $scope object
$scope.product = yourData;
}, function (error) {
console.log('error occured!!');
});
You will do fine now, you don't need to change the response from web api now.
Related
Here I'm using Angularjs1.x and here is my condition. If condition is success then show the table otherwise throw an error. I know some code if its Success.
AngCtrl.Js
$scope.BtnCall = function () {
ServiceCntrl.CallData().then(function (d) {
$scope.EmpData = d.data;
});
}
AngService.Js
eApp.service("ServiceCntrl", function ($http) {
var xx = '';
xx= $http({
data: formData,
method: 'post',
url: Url,
datatype: "json"
}).success(function (rsp) {
RspData = rsp;
return RspData;
}).error(function (rsp) {
console.log('Error');
});
return xx;
};
Your x.then receives two functions x.then(function(){}, function(){}); first function is called when promise is successfully resolved and second function is called if promise is rejected(failed).
If your service function is return $http promise then your first function can have a parameter named(anything you like) and it will have response data that you can use. Second function can receive error parameters if any.
you should look at angular $http service documentation.
If your service is returning the promise of the get request, then you can write
$scope.BtnCall = function () {
var x = ServiceCntrl.CallData();
x.then(function(response) {
//Success callback
//code on success goes here
//response.data
}, function(response) {
//error callback
//code on error goes here
// server returns response with an error status.
});
you can use the ng-show/ng-hide to show and hide the contents on the html page.
You can write your success/fail code as the following:
$scope.BtnCall = function() {
var x = ServiceCntrl.CallData();
x.then(function(result) {
// Success code here
// Do something and resolved the promise
}, function(reason) {
// Error code here
// You may handle/reject the reason in params
});
});
See also the Angular docs for $q.
The AngularJS $http service makes a request to the server, and returns a response
The example above executes the $http service with an object as an argument. The object is specifying the HTTP method, the url, what to do on success, and what to do on failure.
$scope.BtnCall = function () {
ServiceCntrl.CallData().then(function (d) {
$scope.EmpData = d.data;
});
}
AngService.Js :
eApp.service("ServiceCntrl", function ($http) {
var xx = '';
xx= $http({
data: formData,
method: 'post',
url: Url,
datatype: "json"
}).success(function (rsp) {
RspData = rsp;
return RspData;
}).error(function (rsp) {
console.log('Error');
});
return xx;
};
I've create a function in angular. And it is working fine and can get correct result but my problem is i want particular node from result. i have worked with JSON and Jquery, but i am new in angular.
This is my code.
$scope.booking= function(docid,addid){
//console.log(addid);
var a = $http({
method: 'POST',
url: "http://localhost:81/DoctorStayServiceAngular/model/getDoctorBookingDetail.php",
params:{"doctorid":docid,"addressid":addid,"day":weekday[d.getDay()]}
//params:{"doctorid":docid}
}).then(function mySucces(response) {
//$scope.count= response.data;
/*$scope.appo=[];
$scope.appo= i;
i++;*/
//
//console.clear();
return response.data;
});
console.log(a);
return a;
};
http://localhost:81/DoctorStayServiceAngular/model/getDoctorBookingDetail.php
return following json.
{
"status":"success",
"message":"",
"booking":{
"booking_detail":[{
"session":null,
"slot":null,
"day":"Friday"
}]
}
}
This how i can see in firebug
Expanded view
so i want to get value(which I've highlighted in image) from response(which is under $$state), what should i do?
in short how can i get bottom result?
{
"status":"success",
"message":"",
"booking":{
"booking_detail": [{
"session":null,
"slot":null,
"day":"Friday"
}]
}
}
$http service returns a promise(this is printed in your console logs), which will be resolved after that http call is complete.
Please go through this $q documentation on how deferred data works.
https://docs.angularjs.org/api/ng/service/$q
This should work,
$scope.booking= function(docid,addid){
$http({
method: 'POST',
url: "http://localhost:81/DoctorStayServiceAngular/model/getDoctorBookingDetail.php",
params:{"doctorid":docid,"addressid":addid,"day":weekday[d.getDay()]}
//params:{"doctorid":docid}
}).then(function mySucces(response) {
$scope.responseData = response.data;
});
};
After this you can bind the data in responseData to your view.
I am trying to display results from the database but I am getting this error message
TypeError: Cannot read property 'Result' of undefined
I am creating a Single Page Application using AngularJS. The Result is at the services.js. Can someone help me to solve this error.
This is my services.js code:
(function () {
'use strict';
/** Service to return the data */
angular.module('MovieApp').
service('dataService', // the data service name, can be anything we want
['$q', // dependency, $q handles promises, the request initially returns a promise, not the data
'$http', // dependency, $http handles the ajax request
function($q, $http) { // the parameters must be in the same order as the dependencies
/*
* var to hold the data base url
*/
var urlBase = '/cm0665-assignment/server/index.php';
var loginUrl = '/cm0665-assignment/server/login.php';
/*
* method to retrieve courses, or, more accurately a promise which when
* fulfilled calls the success method
*/
this.getCategories = function () {
var defer = $q.defer(), // The promise
data = {
action: 'listCategory',
//subject: 'category'
};
$http.get(urlBase, {params: data, cache: true}). // notice the dot to start the chain to success()
success(function(response){
defer.resolve({
data: response.ResultSet.Result, // create data property with value from response
rowCount: response.RowCount // create rowCount property with value from response
});
}). // another dot to chain to error()
error(function(err){
defer.reject(err);
});
// the call to getCourses returns this promise which is fulfilled
// by the .get method .success or .failure
return defer.promise;
};
this.getMovies = function (categoryid) {
var defer = $q.defer(),
data = {
action: 'listFilms',
//subject: 'films',
category_id: categoryid
}
$http.get(urlBase, {params: data, cache: true}).
success(function(response){
defer.resolve({
data: response.ResultSet.Result,
rowCount: response.RowCount
});
}).
error(function(err){
defer.reject(err);
});
return defer.promise;
};
this.getActors = function (filmid) {
var defer = $q.defer(),
data = {
action: 'listActors',
film_id: filmid
}
$http.get(urlBase, {params: data, cache: true}).
success(function(response){
defer.resolve({
data: response.ResultSet.Result,
rowCount: response.RowCount
});
}).
error(function(err){
defer.reject(err);
});
return defer.promise;
};
this.getAllMovie = function () {
var defer = $q.defer(),
data = {
action: 'listFilms'
}
$http.get(urlBase, {params: data, cache: true}).
success(function(response){
defer.resolve({
data: response.ResultSet.Result,
rowCount: response.RowCount
});
}).
error(function(err){
defer.reject(err);
});
return defer.promise;
};
this.getSearchResult = function () {
var defer = $q.defer(),
data = {
action: 'search',
// term: terms
}
$http.get(urlBase, {params: data, cache: true}).
success(function(response){
defer.resolve({
data: response.ResultSet.Result,
rowCount: response.RowCount
});
}).
error(function(err){
defer.reject(err);
});
return defer.promise;
};
this.login = function (userID, passwd) {
var defer = $q.defer(),
data = {
//action: 'loginRob',
userid: userID,
password: passwd
};
$http.post(loginUrl, data). // notice the dot to start the chain to success()
success(function (response) {
defer.resolve({
data: response.status, // create data property with value from response
result: response,
user: response.username
});
console.log(response);
}). // another dot to chain to error()
error(function (err) {
defer.reject(err);
});
return defer.promise;
};
}
]
);
}());
Each line of the of the ResultSet is showing this error. This means each time i click on other navigation tab i am showing this error message. I really need someone help on this. Thank you in advance.
You are getting this error because you are trying to dereference a variable that is undefined. In this case it looks like it is caused by the statement: response.ResultSet.Result. The error indicates that response.ResultSet is undefined.
This means that the response from the server isn't in the format you expected, or there is a bug in the server-side code.
I am learning AngularJS and have the structure of the project set up but when i call the API that returns me JSON i can't display that in the html.
The idea is you click on the button and the returned result will be displayed in {{answer}}.
HTML:
<div ng-app="xileapp">
<div ng-controller="searchController">
<input type="button" ng-click="search()" value="search" />
<div>Answer: {{answer}}</div>
</div>
</div>
Controller:
xile.controller('searchController', ['personSearch', '$scope', function (personSearch, $scope) {
$scope.search = function () {
$scope.answer = personSearch.findPlayer();
}
}]);
Service:
xile.service('personSearch', function ($http) {
this.findPlayer = function() {
$http({
method: 'GET',
url: 'https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/Crucify?api_key=222015c4-0898-4f6b-a7d5-2a23c3e0344d'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
return response;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
return response;
});
};
});
The URL is hitting success with the correct response. How do I now get the data to display in the HTML.
Angular has a Json filter you can add to the actual binding expression, once you have the json back.
{{ answer | json }}
If you want the actual json from the response, you can find it in the data property of the response object.
response.data
Improvement suggestion:
I've also provided a 'nicer' short hand for your http get method which I think its actually better because it'll handle any exceptions that gets thrown rather than using an error callback in your case.
return $http.get(apiUrl)
.then(successCB)
.catch(errorCB);
You are not assigning any data to the answer (actually assigning undefined) because findPlayer doesn't return anything.
So first of all, you need to make service method return promise object:
this.findPlayer = function() {
var url = 'https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/Crucify?api_key=222015c4-0898-4f6b-a7d5-2a23c3e0344d';
return $http({
method: 'GET',
url: url
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
return response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
return response;
});
};
then consume it in controller:
$scope.search = function () {
personSearch.findPlayer().then(function(data) {
$scope.answer = data;
});
}
Please log this JSON object and figure out proporty you want display
{answer: "a"}
then
your view will be as
<div>Answer: {{answer.answer}}</div>
and return data from findPlayer function or promise
I know that the data is coming from the server (I have unit tests and have seen the data in the debugger in chrome) but I can't figure out how to return the data from the angular service to the angular controller.
Service:
UPDATED
surchargeIndex.service('customerService', [
'$http', function ($http) {
this.getTest = function () {
return $http({
method: "GET",
url: "api/Customer/GetTest",
})
.success(function(data) {
return data;
});
};
}
]);
Controller:
surchargeIndex.controller('SurchargeIndexController', function ($scope, customerService, templateService) {
$scope.customers = customerService.getTest();
});
Data has the array from the server so the array is populated in the service. So to reiterate the data is there; however, I receive a 404 error INSIDE of the success handler during debugging.
What am I missing?
$http works asynchronously; fortunately it returns a promise which will be fulfilled when the response retrieved from the server. So you should return $http's get method and use returned promise to handle data.
this.getTest = function () {
return $http({
method: "GET",
url: "api/Customer/GetTest",
})
.success(function(data) {
return data;
})
.error(function() {
alert("failed");
}); // This returns a promise
};
Then in your controller you should use that promise to retrieve the expected data.
surchargeIndex.controller('SurchargeIndexController', function ($scope, customerService, templateService) {
//Use the returned promise to handle data, first parameter of the promise is used for successful result, if error happens, second parameter of the promise returns the error and you can do your error handling in that function
customerService.getTest().then(function(customers){$scope.customers = customers;}, function(err){console.error(err);})
});
You need to define a Callback to get your data "back" to your controller, after an async http call... There are different ways to do... I will show you one way without a callback, or a promise, but the best way would be to use a callback, or promise...
Wild West Way:
app.controller('myCTRL', function($scope, myService) {
$scope.valueWanted = myService.valueWanted;
myService.getData();
});
app.service('myService', function($http) {
var myThis = this;
this.valueWanted = "";
this.getData = function () {
$http.get('api/Customer/GetTest').success(function (data) {
myThis.valueWanted = data.valueWanted;
});
};
});