how to pass http data from service to controller in angularjs - 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;
});
});

Related

return a value from $get factory method when calling service from controller in AngularJs

Im trying to call service from controller which gives me below error..
Provider 'loginService' must return a value from $get factory method.
Below is my code.What is that im doing wrong.
CONTROLLLER CODE
app.controller('loginController', ['$scope', '$http', 'loginService', function ($scope, $http, loginService) {
$scope.checkdata = function () {
var userName = $scope.username;
var password = $scope.password;
//Call the login service
loginService.validateUser(userName, password);
alert(response.data);
}
}])
Service code
app.factory('loginService', function ($http) {
this.validateUser = function (userName, password) {
var userData = new Object();
userData.userName = userName;//Data.username;
userData.password = password;//Data.password;
return $http({
url: "http://localhost:53181/api/User",
dataType: 'json',
method: 'POST',
data: userData,
headers: {
"Content-Type": "application/json"
}
}).then(function (response) {
alert(response);
if (response.data && response.data.data && response.data.data.length == 1)
return response.data.data[0];
});
}
});
Create service funtcion like this:
yourAPICallingFuntion: function() {
var url = "your url";
var deferred = $q.defer();
$http.get(url, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(function(data) {
deferred.resolve(data.data);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
In Controller Call like this:
loginService.yourAPICallingFuntion().then(function(data){
//Now this will give you response in form of data
//you can this data according to your requirement
});
factory service is expected to return a value from factory function. It doesn't have this context (it's either window or undefined).
If you want to use this like this.validateUser = ..., use service service instead.

Angularjs $http then is not working properly

I get a value of "True" in my response. How come my debugger and alert and AccessGranted() in the .then of my $http is not being invoked. Below is my Script:
app.controller("LoginController", function($scope, $http) {
$scope.btnText = "Enter";
$scope.message = "";
$scope.login = function() {
$scope.btnText = "Please wait...";
$scope.message = "We're logging you in.";
$http({
method: 'post',
url: '/Login/Login',
data: $scope.LoginUser
}).then(function (response) {
debugger;
alert(response.data);
if (response.data == "True") {
AccessGranted();
} else {
$scope.message = response.data;
$scope.btnText = "Enter";
}
},
function (error) {
$scope.message = 'Sending error: ' + error;
});
}
$scope.AccessGranted = function() {
window.location.pathname("/Home/HomeIndex");
}
});
This is in my HomeController
public ActionResult HomeIndex()
{
var am = new AuditManager();
var auditModel = new AuditModel()
{
AccountId = 0,
ActionDateTime = DateTime.Now,
ActionName = "Home",
ActionResult = "Redirected to Home"
};
am.InsertAudit(auditModel);
return View("Index");
}
Please see image for the response I get.
seems like your approach is wrong
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Try this,
$http({
method: 'post',
url: '/Login/Login',
data: $scope.LoginUser
})
.then(function (response) {
console.log(response);
},
function (error) {
console.log(error);
});
And check your browser console for logs or any errors
Make sure the response is application/json content type, and content is json.
You can also write own httpProvider for check result from server
module.config(['$httpProvider', function ($httpProvider) {
...
I would suggest you to code like this instead of then so whenever there is success, The success part will be invoked.
$http.get('/path/').success(function (data) {
$scope.yourdata = data.data;
//console.log($scope.yourdata);
}).error(function (error){
//error part
});

Delay $http.get call without affecting angularjs promise

Please note that I already read all the StackOverflow questions that are somewhat related to my questions but none of these really answer my question. Please don't mark this as duplicate without fully understanding my question.
Here's my concern:
I would like to delay angularJS $http.get call without affecting the angular promise. Right now the code below throws a "angular-1.3.15.js:11655 TypeError: Cannot read property 'then' of undefined" in this line:
updatedPromise = promise.then(function(price)
Here's my partial code:
MyAPP.service('FirstService', ['$q','$http', 'Constants', 'SecondService', 'UtilityService', function($q, $http, Constants, SecondService, UtilityService) {
var self = this;
var processFunction = function(AnArray) {
var updatedPromise;
var promises=[];
angular.forEach(AnArray, function(itemObj, index)
{
var totalWorth = "";
if(itemObj.name != "")
{
var promise = SecondService.getPrice(itemObj.name);
updatedPromise = promise.then(function(price){
itemObj.price = price;
return itemObj;
}, function(error){
console.log('[+] Retrieving price has an error: ', error);
});
promises.push(updatedPromise);
}
else
{
console.log("Error!");
}
});
return $q.all(promises);
};
);
MyAPP.service('SecondService', ['$timeout','$http', 'Constants', function($timeout, $http, Constants) {
var self = this;
var URL = "/getPrice";
self.getPrice = function(itemName){
$timeout(function(){
var promise;
promise = $http({
url: URL,
method: 'POST',
data: {_itemName : itemName},
headers: {'Content-Type': 'application/json'}
}).then(function(response) {
return response.data;
}, function(response) {
console.log("Response: " + response.data);
return response.data;
});
return promise;
}, 3500);
console.log("[-]getPrice");
};
}]);
Please note that the processFunction should really return an array of promises because this is needed in other functions.
Your help will be highly appreciated!
Let me know for further questions/clarifications.
Thanks!
$timeout returns a promise, so you can return that, and then return the promise from $http:
self.getPrice = function (itemName) {
return $timeout(3500).then(function () {
return $http({
url: URL,
method: 'POST',
data: { _itemName: itemName },
headers: { 'Content-Type': 'application/json' }
});
}).then(function (response) {
return response.data;
}, function (response) {
console.log("Response: " + response.data);
return response.data;
});
};

Error: $ is not defined (Angularjs )

When i call submit function it calls but give error like this , what is the error in this function .
Error: $ is not defined
$scope.submit#http://localhost/angularAjax/app.js:19:21
Mc/u/<#https://code.angularjs.org/1.0.3/angular.min.js:70:297
dc[c]</</</<#https://code.angularjs.org/1.0.3/angular.min.js:140:1
Sc/this.$get</e.prototype.$eval#https://code.angularjs.org/1.0.3/angular.min.js:86:306
Sc/this.$get</e.prototype.$apply#https://code.angularjs.org/1.0.3/angular.min.js:86:412
dc[c]</</<#https://code.angularjs.org/1.0.3/angular.min.js:140:505
pc/c/<#https://code.angularjs.org/1.0.3/angular.min.js:22:460
m#https://code.angularjs.org/1.0.3/angular.min.js:6:191
pc/c#https://code.angularjs.org/1.0.3/angular.min.js:22:433
Here is code :
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$scope.hello = {name: "Boaz"};
$scope.newName = "";
/*$scope.sendPost = function() {
var data = $.param({
json: JSON.stringify({
name: $scope.newName
})
});
$http.post("/echo/json/", data).success(function(data, status) {
$scope.hello = data;
})
} */
$scope.submit = function () {
$http({
method : 'POST',
url : 'pro.php',
data : $.param($scope.contact), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
}) .success(function (data) {
alert(data);
console.log(data);
});
}
});
Angular is working , just ajax call fails
The $.param function you are calling inside $scope.submit is from jQuery. Make sure you are including a reference to jQuery in your page
i think you can convert the data to json, using JSON.stringify like this:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$scope.hello = {name: "Boaz"};
$scope.newName = "";
/*$scope.sendPost = function() {
var data = $.param({
json: JSON.stringify({
name: $scope.newName
})
});
$http.post("/echo/json/", data).success(function(data, status) {
$scope.hello = data;
})
} */
$scope.submit = function () {
$http({
method : 'POST',
url : 'pro.php',
data : JSON.stringify($scope.contact), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
}) .success(function (data) {
alert(data);
console.log(data);
});
}
});

How to do error handling when fetching data in angularjs service

This code fetches categories and give them to controller.
sampleApp.factory('SCService', function($http, $q) {
var SuperCategories = [];
var SCService = {};
SCService.GetSuperCategories = function() {
var req = {
method: 'POST',
url: SuperCategoryURL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "action=GET"
};
if ( SuperCategories.length == 0 ) {
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
});
}else {
return $q.when(SuperCategories);
}
}
return SCService;
});
I think code is perfect until there is no error in http request.
My query is how to do error handling (try catch or something like that), in case if server have some issue or may be cgi-script have some issue and not able to server the request.
Angular promises use a method catch for that.
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
}).catch(function(error) {
// Do what you want here
});
You should use also finally :
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
}).catch(function(error) {
// Do what you want here
}).finally(function() {
// Always executed. Clean up variables, call a callback, etc...
});
Write like
return $http(req).then(function (response) {
//success callback
},
function(){
//Failure callback
});
Use callback methods from controller Like
Controller.js
service.GetSuperCategories(function (data) {console.log('success'},function (error){console.log('error'});
service.js
sampleApp.factory('SCService', function($http, $q) {
var SuperCategories = [];
var SCService = {};
SCService.GetSuperCategories = function(successMethod,errorMethod) {
var req = {
method: 'POST',
url: SuperCategoryURL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "action=GET"
};
return $http(req).then(successMethod(data),
errorMethod(error));
}
return SCService;
});
You can use the .success and .error methods of $http service, as below
$http(req).success(function(data, status, headers){
// success callback: Enters if status = 200
}).error(function(status, headers){
// error callback: enters otherwise
});

Resources