Web api get call but in reponse it says undefined - angularjs

I'm trying to call a web api POST method using angular js it get call.
I try from postman utility it also get call and in respose give a json data.But in angular side i am not getting data in response.
my services in angular js
var _getProjects = function (searchText) {
debugger;
return $http.post(URL + 'api/project/GetProjectDetails?searchText='+ searchText).then(function (response) {
return response;
});
};
and below is my web api
[HttpPost]
[Route("api/project/GetProjectDetails")]
public List<GetKeywordsBasisData_Result> GetProjectDetails(string searchText)
{
if (!String.IsNullOrEmpty(searchText))
{
return projectProvider.GetProjectDetails(searchText).ToList();
}
return new List<GetKeywordsBasisData_Result>();
}

You are missing a callback. Http Calls on $http happen asynchronously, you need to pass in a method to call once the call completes. Something like this. The parameter myCallback is a function that takes in the expected response, you can then process it (or whatever) inside that function.
function (searchText, myCallback) {
$http.post(URL + 'api/project/GetProjectDetails?searchText='+ searchText).then(function (response) {
myCallback(response);
});
};
You can then call it from your controller like this assuming getProjects is your factory method. Also assuming that $scope is a field on your controller.
var me = this;
getProjects('somethingToSearchFor', function(results){
me.$scope.results = results;
});

Related

Http service delay processing until after data is returned

I work on my angularjs project.
I created this service:
(function () {
"use strict";
angular.module("manageItems").factory("manageItemsService", ["$http", "config", manageItemsService]);
function manageItemsService($http, config) {
var service = {
getNewItems: getNewItems,
};
return service;
function getNewItems(session, mapName) {
return $http.get(serviceUrl + 'getNewItems/' + session + "/" + mapName);
}
}
})();
And here how I call the service from controller:
function getNewItems() {
manageItemsService.getNewItems(mapguideService.mapName, mapguideService.sessionId).then(function (result) {
self.currentItems = result.data;
})
}
I need to make service to delay while the response returned.
How can I change servicefunction to make it wait until self.currentItems property is populated by data?
First I need say that http requests are actually performed asynchronously so as not to stop the application while the result is returned.
So you have two options, use the angular pattern to adjust your method in order to treat the result, so you must pass a callback function to the service, so that the service, not the controller make the association. It would be something like:
Service:
(function () {
"use strict";
angular.module("manageItems").factory("manageItemsService", ["$http", "config", manageItemsService]);
function manageItemsService($http, config) {
var service = {
getNewItems: getNewItems,
};
return service;
function getNewItems(session, mapName, callback, errorCallback) {
$http.get(serviceUrl + 'getNewItems/' + session + "/" + mapName).then(callback, errorCallback);;
}
}
})();
Controller:
function getNewItems() {
manageItemsService.getNewItems(mapguideService.mapName, mapguideService.sessionId, function (result) {
//this callback will be called asynchronously when the response is available
self.currentItems = result.data;
}, function(error) {
// called asynchronously if an error occurs
// or server returns response with an error status.
})
}
The second option is to totally not recommended, inserting a loop while the result is expected... (to bad)
I hope I have helped!
Then you could be put up .then on getNewItems $http call. And based on retrieved response data, decide whether to return data or call another service method.
function anotherFunction(){
return $http.get(url);
}
function getNewItems(session, mapName) {
return $http.get(serviceUrl + 'getNewItems/' + session + "/" + mapName).then(function successCallback(response){
var data = response.data;
//call another function if data is empty
if(!data.length)
return anotherFunction(); //make sure another function should return promise
return data;
});
}
What the code needs to do is chain promises.
To make the getNewItems function chainable, return the derived promise:
function getNewItems() {
//vvvv RETURN promise
return manageItemsService.getNewItems(mapguideService.mapName, mapguideService.sessionId)
.then(function (response) {
self.currentItems = response.data;
//RETURN value to chain
return response.data;
});
};
Then use the returned promise to chain more operations:
getNewItems().then( function(currentItems) {
//Evaluate current Items
if ( ok ) {
return "DONE";
} else {
//RETURN to chain something else
return getOtherItems();
};
}).then( function(otherItems) {
if (otherItems == "DONE") return;
//ELSE
self.otherItems = otherItems;
//Do further chaining
});
Because calling the .then method of a promise returns a new derived promise, it is easily possible to create a chain of promises.
It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain. This makes it possible to implement powerful APIs.
— AngularJS $q Service API Reference - Chaining Promises

AngularJS Http get empty first time

I have this code
PedidosService.getProductbyID($scope.listProductos.ProductID).then(function (d) {
$scope.oneProduct = d.data.producto;
});
PedidosService is the name of my factory, getProductbyId is my http get request and $scope.oneProduct is the variable where i want store the result of this request.
factory.getProductbyID = function (id) {
return $http.get('/Pedidos/GetProduct/' + id);
}
factory is my Factory and getProductbyID is my function to call http request
I call this code in a button. The first time that I click in the button, it returns a empty response '[]' but the next times that I click the button, it works fine!!!.
Thanks for you help
As far as I know the $http.get returns a promise because that call is asynchronous. With that in mind a typical call to $http.get should be something like this:
$http.get('/someUrl', config).then(successCallback, errorCallback);
In your context I would have done it this way, so the factory returns a promise and in your controllers you will handle the success and error callback appropriately:
factory.getProductbyID = function (id) {
var deffered = $q.defer();
$http.get('/Pedidos/GetProduct/'+ id)
.then(function (result) {
deffered.resolve(result);
}, function (data) {
deffered.reject(data);
});
return deffered.promise;
}

how to have angularJS post data to MVC controller which redirects to a view

I am posting some data to an MVC action method using AngularJS. This action method will either show its backing view or redirect to another page. Currently all that is happening is the data is getting posted but the redirect is not happening via MVC. I am getting this done using angular's window.location method. I want to know if there is a better way or if I need to post differently using Angular.
On page A I have angular scripts posting data to page B like below:
serviceDataFactory.POST('http://localhost:1234/home/B', someData, pageConfig).then(function () {
//on success
window.location = 'http://localhost:1234/home/Index';
},
function() {
//on error
window.location = 'http://localhost:1234/home/B';
});
This is my service factory
app.factory('serviceFactory', function($http, $q) {
var service = {};
//POST
service.POST = function (url, postData, conf) {
var d = $q.defer();
$http({
method: 'POST',
url: url,
data: postData,
config: conf
}).success(function(data) {
d.resolve(data);
}).error(function(error) {
d.reject(error);
});
return d.promise;
}
return service;
}
);
On Page B I want to redirect to another page. This is my page B in MVC
[HttpPost]
public ActionResult B(string someData)
{
//recieve string someData and perform some logic based on it
.
.
.
if(boolCondition)
return RedirectToAction("Index", "Home");
else
return View();
}
Here once Angular posts to the action method B, it executes all the code all the way till the if(boolCondition) statement. Since I am unable to have that redirect affected via MVC, I do that in Angular itself using the success or error block that the promise returns to.
I want to know if there is a better way to do this or if I am doing something wrong here or if this is the only acceptable way. How do I get angular to hand-off to the MVC action method and let further redirects continue from there only?
You should not use the .success() / .error() pattern with $http, because this has been deprecated. Instead, use then() with two arguments, the first argument being the success function and the second being the error function.
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
You do not need to promisify the result of $http, because $http returns a promise. Just return $http from your service.
app.factory('serviceFactory', function($http, $q) {
var service = {};
//POST
service.POST = function (url, postData, conf) {
return $http({
method: 'POST',
url: url,
data: postData,
config: conf
});
}
return service;
});
Your Page A controller will work the same as before with this new simplified code. At the server, be sure to emit a 500 http status code in cases where you want to trigger the
function() {
//on error
window.location = 'http://localhost:1234/home/B';
}
to run. The 500 in the headers of the response will cause the AngularJS promise to run the second function in your controller.

Retrieving data using $http.post

Hi I want to get data from my json file using post method(which is working 5n with get method)
'use strict';
angular.module('myapp').controller('lastWeekWinners',function($http){
var vm= this;
$http.post('http://localhost:9000/json/sample.json').then(function(data){
vm.winnerData=data.data.data;
},function(error){
console.log(error);
});
});
the about code is give error
which means can't we use post method to get the data
This is how u can use the post method in your controller:
'use strict';
angular.module('myapp').controller('lastWeekWinners', controller){
function controller($scope,fetch){
var vm= this;
vm.show = show;
}
function show() {
return fetch.show()
.then(function successCallback(data){
vm.winnerData = data;
}
}, function errorCallback (response) {
console.log(response.statusText);
});
}
});
and in your service :
angular
.module('service',[])
.service('fetch', Service);
function Service($http) {
var fetch = {
show : show
}
return fetch;
function show() {
return $http.get('http://localhost:9000/json/sample.json')
.then(getShowComplete)
.catch(getShowFailed);
function getShowComplete(response){
return response.data;
}
function getShowFailed(error){
console.log("Error:" + error);
}
}
First of all, the difference between GET/POST:
GET is used for getting data, POST is used for saving (and sometimes updating) data. So if you just want to get the json, use GET.
Regarding the specific problem you have here, if you look carefully, you get a 404 code. that means the route was not found. (You can read more about HTTP status code here: http://www.restapitutorial.com/httpstatuscodes.html)
Not sure what server you're using but usually, you're not only defining a route but also the verb of the route (GET/POST/PUT/DELETE), so if you have a route defined like:
GET /users/
This will only work for GET requests, if you try to post for the same route you'll get 404. You have to define the same route for the POST verb.
You can read more about http verbs here: http://www.restapitutorial.com/lessons/httpmethods.html
To do $http.post you need a back end API(PHP,Node Js etc),that system catch your desired post data and save into the db or JSON(Read/Write Method).
Static JSON data just read only possible not write.
Or used Browser $window.localStorage to save data.

Trying to make a $resource call from a controller through a model to a service, can't get the response back to the controller

I've got a controller that has a dependency on a model. It calls
AccountModel.saveAccount(vm.Account,function(data){
response = data;
},function(data){
response = data;
});
The model calls a service's save function:
return AccountService.save(request,function(resp){
return resp;
},function(resp){
return resp;
});
and that function looks like this:
function save(Account) {
return AccountResource.save(Account, function (resp) {
return resp;
}, function (resp) {
return resp;
});
}
The idea is that the save function will return the response to the model which will return it to the controller, which will do other stuff later. However, none of this is happening.
response (in the controller) remains undefined. How can I fix this?
Angular's service works a little different, the save method returns and object:
{$promise: promisveValue, $resolve: something}
So to use it properly:
myResource.save(resouceObj, handler);
or
myResource.save().$promise.then(handler);
This is a draft of what you should do, try to integrate this into your code.

Resources