How to get value from $http function in angularjs - javascript

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.

Related

Where to write Success and Error

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

AngularJS Display JSON Data

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

Get object by id using $resource

I am dealing with a little issue, and need some help.
I have an API setup, works just fine.
Now I want to get a single object using its ID. I have tried using $http, but could't get it to work. So I switched back to $resource. Here is what I have in my service file.
getPlatesInSelectedContainer: function() {
return $resource('/api/v1/platesincontainer/:id', {id: "#id" },{
get: { cache: true, method: 'GET' }
});
},
And in controller I am reaching to function doing so.
CleaningPlatesFactory.getPlatesInSelectedContainer({id : 1}, function(data){
$scope.plates = data;
console.log(data);
})
But this is not returning any results. What I am doing wrong?
UPDATE
Earlier I have tried $http but getting this.
I would still get $http to work. It's as simple as this:
getPlatesInSelectedContainer: function(data) {
return $http.get('/api/v1/platesincontainer/' + data.id);
}
You need to accept the data object in your service function.
Inside the service:
getPlatesInSelectedContainer: function(data) {
return $resource('/api/v1/platesincontainer/:id', {id: data.id },{
get: { cache: true, method: 'GET' }
});
}
Then call it like this:
getPlatesInSelectedContainer({ id: 123 })

AngularJS 1.x How do I use resource to fetch an array of results?

This is what I wrote in my factories.js:
app.factory('CustomerCompany', function($resource){
return $resource('/customer_companies/:id.json', {id: "#_id"}, {
'query':{method: 'GET', isArray:false},
'getByCustomerAccount':{
method: 'GET',
params: {customer_account_id: customer_account_id},
isArray:true,
url:'/customer_companies/get_by_account/:customer_account_id.json'
}
});
});
Because I want to fetch a list of customer_companies that belong to a particular customer_account so I need to supply a customer_account_id.
In my controllers.js,
app.controller('customerAccountEditController', function($scope, CustomerCompany) {
$scope.data = {};
var path = $location.path();
var pathSplit = path.split('/');
$scope.id = pathSplit[pathSplit.length-1];
var customer_account_id = $scope.id;
$scope.list_of_companies = [];
CustomerCompany.getByCustomerAccount({customer_account_id: customer_account_id}, function(data){
console.log(data);
//$scope.list_of_delegates.push(data);
});
});
I get a customer_account_id not defined.
Where did I go wrong?
I think you don't need to define params inside your $resource & then URL will becomes url:'/customer_companies/get_by_account/customer_account_id.json' & while calling a method you need to pass the customer_account_id, from {customer_account_id: customer_account_id} so that it would create an URL with customer_account_id=2 somtehing like that.
Service
'getByCustomerAccount':{
method: 'GET',
//params: {customer_account_id: customer_account_id}, //removed it
isArray:true,
url:'/customer_companies/get_by_account/:customer_account_id'
}
Controller
CustomerCompany.getByCustomerAccount({customer_account_id: customer_account_id + '.json'}, function(data){
console.log(data);
//$scope.list_of_delegates.push(data);
});
This worked for me.
controllers.js
CustomerCompany.getByCustomerAccount({customer_account_id: customer_account_id}, function(data){
console.log(data);
//$scope.list_of_delegates.push(data);
});
services.js
app.factory('CustomerCompany', function($resource){
return $resource('/customer_companies/:id.json', {id: "#_id"}, {
'query':{method: 'GET', isArray:false},
'getByCustomerAccount':{
method: 'GET',
isArray:false,
url:'/customer_accounts/:customer_account_id/customer_companies.json'
}
});
});
What I changed:
on the server side, I decided to use /customer_accounts/:customer_account_id/customer_companies to render the results.
I realized that the data returned is always in object form, so I changed isArray in the $resource to false.
I pass the params like the way the Pankaj Parkar suggested in the controller when I call getByCustomerAccount
params: {customer_account_id: customer_account_id},
The customer_account_id you try to assign here is not defined.
Try params: {customer_account_id: '#customer_account_id'},

AngularJS $http request object for another request

Sorry for the confusing title, basically I have a json file that looks like this that points to other locations:
{
"link": [
{
"href": "some-external-resource",
"title": "services-path"
}
]
}
My real problem is getting the href of the object to not load asynchronously into the Angular service. The following is my request to the above json file:
var servicesPath = $http({
url: 'resource-directory.json',
method: "GET"
}).success(function(data){
return $filter('filter')(data.link, {title: "services-path"})[0].href;
});
console.log(servicesPath);
I know what is being returned is what I want, but the console log returns the standard "then, catch, finally, success, error" object functions, meaning the data isn't there when I need it. How can I manipulate my request so the variable contains the information?
Since you have an async call, the value would be returned when the call is finished (successfully)
$http({
url: 'resource-directory.json',
method: "GET"
}).success(function(data){
console.log('response data', data);
var theHref = $filter('filter')(data.link, {title: "services-path"})[0].href;
console.log('theHref', theHref); // value shows here
}).error(function(errorResp){
console.log('error');
});

Categories