Converting $.ajax call to $http call in angular 404 error - angularjs

I'm working on converting a jquery ajax call to an angular $http call, but for some reason am returning a 404 status. Here is the original jquery call.
function getStaffInfo(){
$.ajax({
url: 'https://my.website.com/j/wkr/stafflist.php',
data: {f: 'staff'},
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'vcLoadStaff',
success: function(){
//alert("success");
}
});
}
Here is the angular $http call:
app.service('staffList', function($http){
var staffList = {};
$http.jsonp('https://my.website.com/j/wkr/stafflist.php', {"f":"staff"})
.success(function(data, status, headers, config) {
console.log(data);
staffList = data;
}).error(function(data, status, headers, config) {
console.log(status);
});
return staffList;
});
Am I missing something in my angular code?

I believe you need to append ?callback=JSON_CALLBACK to your URL.
$http.jsonp('https://my.website.com/j/wkr/stafflist.php?callback=JSON_CALLBACK', {"f":"staff"})
.success(function(data, status, headers, config) {
console.log(data);
staffList = data;
}).error(function(data, status, headers, config) {
console.log(status);
});
Edit: Just to clarify, when you make that change, the resulting data will be wrapped in JSON_CALLBACK([...]). Also check out this relevant answer.

The http service returns the payload as a promise so you may find you have to call success on the service inside the controller you are using it in like so..
app.service('staffList', function ($http) {
return {
getList: function () {
$http.jsonp('https://my.website.com/j/wkr/stafflist.php?callback=JSON_CALLBACK', {"f":"staff"})
}
};
});
app.controller('staffController', [$scope, staffList,
function($scope, staffList) {
staffList.getList().success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, headers, config) {
console.log(status);
});
}
]);
The angular $q service may also be useful although I found the above implementation some what easier to use.
https://docs.angularjs.org/api/ng/service/$q

At angular documentation your $http.jsonp can be like this:
jsonp(url, [config]);
So you may try
$http.jsonp('https://my.website.com/j/wkr/stafflist.php', {data:{"f":"staff"}})
https://docs.angularjs.org/api/ng/service/$http#jsonp

Related

using the data from the post request

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

401 Unauthorized error with $http and hedear param in in angularjs

I am trying to a $http request with passing header params for login page, but its return 401 Unauthorized error. I have no idea any wrong code done.
var app = angular.module('myApp', [])
.controller('myCtrl', ['$scope', '$http', function($scope, $http){
var params = {"Username":"test", "Password":"test"};
$http.post('http://192.168.6.168:9090/EOZAPI/api/1.0/secure/login/', {headers: params
}).success( function (data, status, headers, config) {
console.log(headers());
})
.error( function (data, status, headers, config) {
console.log(headers());
});
}]);
why not just pass params? I m sure you ll need some more params if its is giving you an unauthorized error Response.
the JSON sent as parameter should be
$http.post('http://192.168.6.168:9090/EOZAPI/api/1.0/secure/login/', params)
.success( function (data, status, headers, config) {
console.log(headers());
})
.error( function (data, status, headers, config) {
console.log(headers());
});
OR If you need to set some header:
$http.post('http://192.168.6.168:9090/EOZAPI/api/1.0/secure/login/',
{headers: someHeaderJson, data: params})
.success( function (data, status, headers, config) {
console.log(headers());
})
.error( function (data, status, headers, config) {
console.log(headers());
});
PS: this is the code on angular's site. Found on this page
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
PS2: Try using POSTMAN or something to verify if the requested URL i.e. http://192.168.6.168:9090/EOZAPI/api/1.0/secure/login/ is working or not.

AngularJS : service not returning value

I'm trying to write an Angular service and it seems like there is something missing. My problem is its not returning any value to my Angular controller
getPrepTimes() method is not returning the http data
But when I check the network (via Chrome dev tools) it will correctly call the external api and return a json object as a response
#my service
'use strict';
angular.module('recipeapp')
.service('prepTimeService',['$http', function($http){
this.prepTime = getPrepTimes();
function getPrepTimes(){
$http({
url: '/prep_times/index.json',
method: 'GET'
})
.success(function (data, status, header, config){
return data;
});
};
}
]);
#controller
'use strict';
angular.module('recipeapp')
.controller('recipeCtrl', ['$scope', 'prepTimeService', function($scope, prepTimeService){
$scope.prep_time = prepTimeService.prepTime;
}]);
When I checked the method getPrepTimes() with returning a string it works. What could be missing here?
A couple things are wrong with the above. You assign this.prepTime to getPrepTimes(). The () there will invoke getPrepTimes immediately, and not when you actually call it! You also need to utilize callbacks to get your data back and use it:
angular.module('recipeapp').service('prepTimeService',['$http', function($http){
this.prepTime = getPrepTimes;
function getPrepTimes(callback) {
$http({
url: '/prep_times/index.json',
method: 'GET'
}).success(function (data, status, header, config){
callback(data);
});
};
}]);
And now use it like so:
prepTimeService.prepTime(function(data) {
$scope.prep_time = data;
});
Calls to the $http service are async, which means you need to return a promise (and not a value):
this.prepTime = function() {
return $http({
url: '/prep_times/index.json',
method: 'GET'
});
};
And on the controller:
angular.module('recipeapp')
.controller('recipeCtrl', ['$scope', 'prepTimeService', function($scope, prepTimeService){
$scope.prep_time = prepTimeService.prepTime()
.success(function (data, status, header, config){
$scope.someVar = data;
});
}]);
Wrap answer with promise:
var self = this;
var deferred = $q.defer();
self.getPrepTimes = function() {
$http({
url: '/prep_times/index.json',
method: 'GET'
})
.success(function(data, status, headers, config) {
if (data.error === undefined) {
deferred.resolve(data);
} else {
if (data.error !== undefined) {
} else {
deferred.reject(data);
}
}
}).error(function(data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
};
In controller call it:
prepTimeService.getPrepTimes().then(function(result) {
$scope.prep_time = result;
},
function(error) {
// show alert
});

How can I make a function call depend on completion of two $http calls in AngularJS?

In my controller I have the following calls:
optionService.init($scope);
optionService.getSubjects1($scope);
optionService.getSubjects2($scope);
optionService.getAbc($scope);
Here's the code for the optionService:
angular.module('common')
.factory('optionService',
['$http',function ($http) {
var factory = {
init: function ($scope) {
$scope.option = {};
},
getSubjects1: function ($scope) {
var url = '/api/Subject1/GetSelect';
$scope.loading++;
$http.get(url)
.success(function (data, status, headers, config) {
$scope.option.subjects1 = data;
$scope.loading--;
})
.error(function (data, status, headers, config) {
$scope.loading--;
alert("Error: No data returned from " + url);
});
},
getSubjects2: function ($scope) {
var url = '/api/Subject2/GetSelect';
$scope.loading++;
$http.get(url)
.success(function (data, status, headers, config) {
$scope.option.subjects2 = data;
$scope.loading--;
})
.error(function (data, status, headers, config) {
$scope.loading--;
alert("Error: No data returned from " + url);
});
},
}
return factory;
}]);
Is there a way that I could make the call to optionService.getAbc depend on the completion of both the getSubjects1 and getSubjects2 calls? I will also soon be using Angular 1.2 if this makes any difference.
$q.all(promises) lets you combine multiple promises in to one:
optionService.getAbc = function($scope) {
$q.all([
optionService.getSubjects1($scope),
optionService.getSubjects2($scope)
])
.then(function() {
//...
});
}
Edit. Yes, you need to return promises from your getSubjects functions. To keep code changes to bare minimum, you could do something like this:
optionService.getSubjects1($scope) {
var url = '/api/Subject1/GetSelect';
$scope.loading++;
return $http.get(url)
.then(function (data, status, headers, config) {
$scope.option.subjects1 = data;
$scope.loading--;
}, function (data, status, headers, config) {
$scope.loading--;
alert("Error: No data returned from " + url);
});
}
With $http.then() you create a new promise that can be combined with other promises in getAbc()
You should rewrite your getSubject1 and getSubject2 to return promise. Also passing the $scope to the method and updating the scope from the service method is not a good way of doing things. You service methods should return data which assignable in your code. This makes your services more usable and readable.
If you change getSubject1 and getSubject2 in lines of
getSubjects1: function () {
var url = '/api/Subject1/GetSelect';
return $http.get(url);
}
In your controller you can do
$q.all([
optionService.getSubjects1(),
optionService.getSubjects2()
])
.then(function([data1, data2]) {
//use data1 to update scope for subject1
// use data2 to update scope for subject2
//call any service method.
});

AngularJS - Controller gets the data returned from Service (MVC Web API call) as undefined

I am new to AngularJS & working on a sample. In my sample app I have an MVC Web api (which returns some data from db) & it will be called from the Angular Services and returns the data to the Controller. The issue is I am getting the data in my Services success method properly but in my controller it always shows undefined & nothing is displayed in the view. Please see the code below:
My Controller code:
app.controller('CustomerController', function ($scope, customerService) {
//Perform the initialization
init();
function init() {
$scope.customers= customerService.getCustomers();
}
});
My Services code:
app.service('customerService', function ($http){
this.getCustomers = function () {
$http({
method: 'GET',
url: 'api/customer'
}).
success(function (data, status, headers, config) {
return data;
}).
error(function (data, status) {
console.log("Request Failed");
});
}
});
Please help me to fix this issue.
That's because your service defines the function getCustomers but the method itself doesn't actually return anything, it just makes an http call.
You need to provide a callback function in the form of something like
$http.get('/api/customer').success(successCallback);
and then have the callback return or set the data to your controller. To do it that way the callback would probably have to come from the controller itself, though.
or better yet, you could use a promise to handle the return when it comes back.
The promise could look something like
app.service('customerService', function ($http, $q){
this.getCustomers = function () {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'api/customer'
}).
success(function (data, status, headers, config) {
deferred.resolve(data)
}).
error(function (data, status) {
deferred.reject(data);
});
return deferred;
}
});
Your problem is in your service implementation. You cannot simply return data since that is in the asynchronous success callback.
Instead you might return a promise and then handle that in your controller:
app.service('customerService', function ($http, $q){
this.getCustomers = function () {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'api/customer'
})
.success(function (data, status, headers, config) {
// any required additional processing here
q.resolve(data);
})
.error(function (data, status) {
q.reject(data);
});
return deferred.promise;
}
});
Of course if you don't require the additional processing, you can also just return the result of the $http call (which is also a promise).
Then in your controller:
app.controller('CustomerController', function ($scope, customerService) {
//Perform the initialization
init();
function init() {
customerService.getCustomers()
.then(function(data) {
$scope.customers= data;
}, function(error) {
// error handling here
});
}
});
VERY late answer, but, Angular's $http methods return promises, so there's no need for wrapping everything into promise form with $q. So, you can just:
app.service('CustomerService', function ($http) {
this.getCustomers = function () {
return $http.get('/api/customer');
};
});
and then call the .success() or .error() shortcut methods in your client controller.
If you want to take it a step further and have a fully-fledged RESTful CustomerService without having to write this boilerplate, I'd recommend the restangular library, which makes all sorts of methods available to you - assuming of course your backend responds to HTTP verbs in the "standard fashion".
Then you could just do this:
app.service('CustomerService', function (Restangular) {
return Restangular.service('api/customer');
});
and call the methods Restangular makes available to you.
I use this for communication between Angular Web Data Service and Web Api Controller.
.factory('lookUpLedgerListByGLCode', function ($resource) {
return $resource(webApiBaseUrl + 'getILedgerListByGLCode', {}, {
query: { method: 'GET', isArray: true }
});
})
OR
.factory('bankList', function ($resource) {
return $resource(webApiBaseUrl + 'getBanklist_p', {}, {
post: {
method: 'POST', isArray: false,
headers: { 'Content-Type': 'application/json' }
}
});
})

Resources