GET call to REST API returns null - angularjs

I am trying to make a GET call to test a REST API but it keeps returning null, is there anything I am doing wrong:
Making the call in controller.js
function ConsumerSearchCtrl($scope, BusinessCategoryService) {
console.log(BusinessCategoryService);
}
127.0.0.1:8000/api/category/ works perfectly fine
Code in services.js for API
/**
*
*/
function BusinessCategoryService(WenzeyAPI, $q) {
var scope = this;
scope.categories = categories;
function categories() {
var q = $q.defer();
WenzeyAPI.get('http://127.0.0.1:8000/api/category/').then(function success (res) {
q.resolve(res.data);
}, function failure (err) {
q.reject(err);
})
return q.promise;
}
}
/**
*
*/
function WenzeyAPI() {
var scope = this,
ip = "http://127.0.0.1:8000";
scope.get = get;
scope.post = post;
function get(url, data) {
data = data || {};
var req = {
method: 'GET',
url: url,
data: data
}
var q = $q.defer();
$http(req).then(function success(response) {
q.resolve(response);
}, function failure(err) {
q.reject(err);
});
return q.promise;
}
function post(url, data) {
data = data || {};
var req = {
method: 'POST',
url: url,
data: data
}
var q = $q.defer();
$http(req).then(function success(response) {
q.resolve(response);
}, function failure(err) {
q.reject(err);
});
return q.promise;
}
}

Removing WenzeyAPI and using $http resolved it.
function BusinessCategoryService($http) {
this.getAllData = function () {
return $http({
method: 'GET',
url: 'http://127.0.0.1:8000/api/category/',
});
}
}

Related

$q.all() returns an array of undefined values

I have 3 functions that request data from backend. Following is the code in the controller.js file
$scope.getList1 = = function () {
service.getList1(constants.getUrl1).then(
function success(data) {
$scope.list1 = data.data.list1;
return data;
}, function error() {
});
};
$scope.getList2 = = function () {
service.getList2(constants.getUrl2).then(
function success(data) {
$scope.list2 = data.data.list2;
return data;
}, function error() {
});
};
$scope.getList3 = = function () {
service.getList3(constants.getUrl3).then(
function success(data) {
$scope.list3 = data.data.list3;
return data;
}, function error() {
});
};
And in my service.js file, I have $http requests to fetch the data from the server. Following is my code in the service.js
this.getList1 = function (getUrl1) {
return $http({
method: 'GET',
url: getUrl1
});
};
this.getList2 = function (getUrl2) {
return $http({
method: 'GET',
url: getUrl2
});
};
this.getList3 = function (getUrl3) {
return $http({
method: 'GET',
url: getUrl3
});
};
then I in a separate function I have called like below
$scope.initialise = function () {
var requestArray = [$scope.getList1(), $scope.getList2(), $scope.getList3()];
$q.all(requestArray).then(function (response) {
console.log(response);
//other logic after successful completion of all 3 requests
});
};
But in the response, I get an array of 3 'undefined' values
e.g [undefined, undefined, undefined]
What am I doing wrong here. Any suggestions ?.
Thanks.
Add return statement in functions in your $scope.
$scope.getList1 = = function () {
/** here-> */ return service.getList1(constants.getUrl1).then(
function success(data) {
$scope.list1 = data.data.list1;
return data;
}, function error() {
});
};
And so on.
Issue is that your functions in service are returning promises, but functions in scope are not returning anything.

Custom method in an Angular service using $resource in Jhipster

I don't understand the syntax to write a custom method in an Angular Service using $resource in Jhipster. After a lot of research, I am doubtful whether it's even possible.
Here is the code for Angular Service.
(function() {
'use strict';
angular
.module('tealboxApp')
.factory('Task', Task);
Task.$inject = ['$resource', 'DateUtils'];
function Task ($resource, DateUtils) {
var resourceUrl = 'api/tasks/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
data.assignedDateTime = DateUtils.convertDateTimeFromServer(data.assignedDateTime);
data.startDateTime = DateUtils.convertDateTimeFromServer(data.startDateTime);
data.endDateTime = DateUtils.convertDateTimeFromServer(data.endDateTime);
data.startDate = DateUtils.convertLocalDateFromServer(data.startDate);
data.endDate = DateUtils.convertLocalDateFromServer(data.endDate);
}
return data;
}
},
'update': {
method: 'PUT',
transformRequest: function (data) {
var copy = angular.copy(data);
copy.startDate = DateUtils.convertLocalDateToServer(copy.startDate);
copy.endDate = DateUtils.convertLocalDateToServer(copy.endDate);
return angular.toJson(copy);
}
},
'save': {
method: 'POST',
transformRequest: function (data) {
var copy = angular.copy(data);
copy.startDate = DateUtils.convertLocalDateToServer(copy.startDate);
copy.endDate = DateUtils.convertLocalDateToServer(copy.endDate);
return angular.toJson(copy);
}
}
});
}
})();
I want to add a custom method like...
'getTasksWithXYZ': {
method: 'GET',
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
data.assignedDateTime = DateUtils.convertDateTimeFromServer(data.assignedDateTime);
data.startDateTime = DateUtils.convertDateTimeFromServer(data.startDateTime);
data.endDateTime = DateUtils.convertDateTimeFromServer(data.endDateTime);
data.startDate = DateUtils.convertLocalDateFromServer(data.startDate);
data.endDate = DateUtils.convertLocalDateFromServer(data.endDate);
}
return data;
}
}
I am not sure how to pass a parameter to this get method or even how to call this method in the controller. How does one do this?
In your service add params
return $resource(resourceUrl, {}, {
'getTasksWithXYZ': {
method: 'GET',
params:{id:'#id'},
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
data.assignedDateTime = DateUtils.convertDateTimeFromServer(data.assignedDateTime);
data.startDateTime = DateUtils.convertDateTimeFromServer(data.startDateTime);
data.endDateTime = DateUtils.convertDateTimeFromServer(data.endDateTime);
data.startDate = DateUtils.convertLocalDateFromServer(data.startDate);
data.endDate = DateUtils.convertLocalDateFromServer(data.endDate);
}
return data;
}
}
})
In your controller Task.getTasksWithXYZ(id)

Common transformResponse in factory $resource

We are using a factory to interact with a series of custom APIs around common entities. However, part of what I need to do is evaluate the custom responses sent back in the headers and it seems like they way to do this is to use transformResponse. What I have seems to be working, but I'm literally repeating the same thing over and over in each definition. I tried creating a function to make it reusable, but the reference seems to fail. What am I doing wrong?
(function()
{
'use strict';
angular.module('aumBills', ['ngResource'])
.factory('Bills', ['$resource',
function($resource)
{
return $resource(
'/ua_aumcore/bills/api/v1/bills/:billableEventI',
{
billableEventI:'#billableEventI'
},
{
getList:
{
method: 'GET',
isArray: false,
transformResponse: function(data, header, status, config, statusText)
{
var response = {};
if (isJson(data))
{
data = angular.fromJson(data);
response.data = data;
}
response.status = status;
response.config = config;
response.statusText = statusText;
return response;
},
url: '/ua_aumcore/bills/api/v1/bills/query/'
},
getParties:
{
method: 'GET',
isArray: false,
transformResponse: function(data, header, status, config, statusText)
{
var response = {};
if (isJson(data))
{
data = angular.fromJson(data);
response.data = data;
}
response.status = status;
response.config = config;
response.statusText = statusText;
return response;
},
url: '/ua_aumcore/bills/api/v1/customer/billParties/?partySites=:partySiteIDs',
params: {partySiteIDs: '#partySiteIDs'}
}
//plus about 12 more after this
});
}]);
function isJson(str)
{
try
{
JSON.parse(str);
}
catch (e)
{
return false;
}
return true;
}
})();
The code that broke looked identical to above, only I put:
transformResponse: transResp(data, header, status, config, statusText),
in each definition, and then this is the function that follows immediately after isJSON:
function transResp(data, header, status, config, statusText)
{
var response = {};
if (isJson(data))
{
data = angular.fromJson(data);
response.data = data;
}
response.status = status;
response.config = config;
response.statusText = statusText;
return response;
}
It looks like defining the transformResponse function I want to use as a variable, and plugging the variable into the definition works:
(function()
{
'use strict';
angular.module('aumBills', ['ngResource'])
.factory('Bills', ['$resource',
function($resource)
{
var transResp = function(data, header, status, config, statusText)
{
var response = {};
if (isJson(data))
{
data = angular.fromJson(data);
response.data = data;
}
response.status = status;
response.config = config;
response.statusText = statusText;
return response;
};
return $resource(
'/ua_aumcore/bills/api/v1/bills/:billableEventI',
{
billableEventI:'#billableEventI'
},
{
get:
{
method: 'GET',
isArray: false,
transformResponse: transResp,
url: '/ua_aumcore/bills/api/v1/bills/:billableEventI'
},
getList:
{
method: 'GET',
isArray: false,
transformResponse: transResp,
url: '/ua_aumcore/bills/api/v1/bills/query/'
}
//and so on and so forth
});
}]);
function isJson(str)
{
try
{
JSON.parse(str);
}
catch (e)
{
return false;
}
return true;
}
})();

how to write controller for this service?

myapp.factory('serviceName', function( $http, webStorage){
var factory = {};
var resoureurlBase=some base url;
factory.genericService = function(method, payload, methodName, callbackFn, callbackError, param) {
var httpRequest = null;
if (param && param == true) {
httpRequest = $http({
url: resoureurlBase+methodName,
method: method,
params: payload,
headers: {
'Content-Type': 'application/json'
}
});
} else {
httpRequest = $http({
url: resoureurlBase+methodName,
method: method,
data: payload,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
httpRequest.then(function(response) {
if (callbackFn && callbackFn.call) {
callbackFn.call(null, response);
}
},
function(response) {
if (callbackError && callbackError.call) {
callbackError.call(response);
}
});
httpRequest.error(function(data, status, headers, config) {
});
};
return factory;
});
/*
I have written service like above how can i handle in controller
i mean
how to write call back function in controller
how to inject
etc..
*/
Simple DI(dependency injection) it into your controller:-
myapp.controller('myCtrl',['$scope','serviceName',function($scope,serviceName){
// use serviceName to call your factory function
}]);
Ref:- https://docs.angularjs.org/guide/di
You need to call service like
serviceName.genericService(--parmas--).then(function(d){
//success
})
because from service serviceName, you're returning a promise that need to resolved using .then only.
Controller
var mainController = function($scope, serviceName) {
var callbackFn = function() {
console.log('Success');
}
var callbackError = function() {
console.log('Error');
}
var parameter = {
param1: 1
},
method = 'something', payload = 100, methodName = 'something';
serviceName.genericService(method, payload, methodName, callbackFn, callbackError, parameter).then(
//success function
function(data) {
//call after call succeed
},
//error function
function(error) {
//call after call error
});
};
myapp.controller('mainController', ['$scope', 'serviceName', mainController()];
Hope this could help you. Thanks.

Angular Http Promise Result

I have a little abstraction I wrote around $http that I use to make calls from a security service. The problem I am having is that during a request that results in a 401, the deferred does not seem to propogate correctly.
I am using it like so, and even if it is a 401 it alerts good... I would expect this to alert bad.
security.login('test', 'password').then(function (r) {
alert('good');
}, function (r) {
alert('bad');
});
Http Wrapper
angular.module('app').provider('http', function () {
return {
$get: ['$http', 'url', function ($http, url) {
function http(config) {
config.headers = {
'X-Requested-With': 'XMLHttpRequest'
};
config.url = url.formatUrl(config.url);
return $http(config);
}
return {
delete: function (url, data) {
return http({ url: url, data: data, method: 'DELETE' });
},
get: function (url) {
return http({ url: url, method: 'GET' });
},
post: function (url, data) {
return http({ url: url, data: data, method: 'POST' });
},
put: function (url, data) {
return http({ url: url, data: data, method: 'PUT' });
}
};
}]
};
});
Security Service
function User() {
this.displayName = '';
this.permissions = [];
}
angular.module('app').provider('security', function () {
var _user = new User();
return {
$get: ['$rootScope', '$q', 'cookie', 'http', 'statePermissions', function ($rootScope, $q, cookie, http, statePermissions) {
function login(params) {
return http.post('SS/auth', params).then(function (response) {
cookie.set('authToken', response.data.authToken);
_user = response.data;
$rootScope.$broadcast('event:loginSuccessful', _user);
return response;
}, function (response) {
cookie.expireNow('authToken');
_user = new User();
$rootScope.$broadcast('event:loginUnsuccessful', _user);
$q.reject(response);
});
}
return {
doesAuthTokenExist: function () {
return angular.isDefined(cookie.get('authToken'));
},
getUser: function () {
return _user;
},
isUserAuthorizedForPermission: function (permission) {
var x;
for (x = 0; x < _user.permissions.length; x++) {
if (_user.permissions[x] === permission) {
return true;
}
}
return false;
},
isUserAuthorizedForState: function (stateName) {
if (angular.isDefined(statePermissions[stateName])) {
return this.isUserAuthorizedForPermission(statePermissions[stateName]);
}
return true;
},
login: function (userName, password) {
return login({ username: userName, password: password });
},
loginWithAuthToken: function () {
var authToken = cookie.get('authToken');
return login({ provider: 'token', authToken: authToken });
},
logout: function () {
return http.post('SS/auth/logout').then(function () {
cookie.expireNow('authToken');
_user = new User();
$rootScope.$broadcast('event:logoutSuccessful', _user);
return true;
});
}
};
}]
};
});
Your $http wrapper looks like it's duplicating the functionality of angular's $resource service. Check out the documentation here: http://docs.angularjs.org/api/ngResource.$resource
After a brief look at your code, it seems like the problem could be with how you're using $q. Try rewriting your login method along these lines.
With insight from here:
http://docs.angularjs.org/api/ng.$q
http://docs.angularjs.org/api/ng.$http
function login(params) {
var deferred = $q.defer();
http.post('SS/auth', params).success(function (response) {
cookie.set('authToken', response.data.authToken);
_user = response.data;
$rootScope.$broadcast('event:loginSuccessful', _user);
deferred.resolve(response);
}).error(function (error) {
cookie.expireNow('authToken');
_user = new User();
$rootScope.$broadcast('event:loginUnsuccessful', _user);
deferred.reject(error);
});
return deferred.promise;
}
Also, just curious why you are using providers here as it's not obvious to me?

Resources