.getAll(...).then is not a function - javascript

I updated Angular to version 1.6.4.
So I had to update .success and .error to .then
Now I get the following error:
TypeError: .getAll(...).then is not a function
The Problem is here in the service:
function getAll(page, size) {
return $http.get(baseUrl + '/jobprofiles?page='+page+'&size='+size, {timeout: 5000}).then(function (response) {
data = response;
}), (function(response) {
alertService.setAlert({'message': 'jobmatch.server.unavailable', 'classified': 'danger', 'lives':1});
});
}
Here is the controller:
if($cookies.get("authenticated")=='true'){
//get a list of all candidateprofiles with the use of a page and a size
candidateprofilesService.getAll($scope.page, $scope.size).then(function() {
$scope.data = candidateprofilesService.getData()._embedded.candidateprofiles;
candidateprofilesService.getAll($scope.page, $scope.size+10).then(function() {
if(candidateprofilesService.getData()._embedded.candidateprofiles.length > $scope.data.length){
$scope.moreData = true;
}
else {
$scope.moreData = false;
}
})
});
}

You service code should be like :
myApp.service('candidateprofilesService', function($http) {
this.getAll = function (page, size) {
// just return the promise , don't evaluate here
return $http.get(baseUrl + '/jobprofiles?page='+page+'&size='+size, {timeout: 5000});
}
this.getData = function(){
// your getData() method body, also just return the promise.
}
});
Then in your controller after injecting service,
candidateprofilesService.getAll($scope.page, $scope.size).then(function(response){
//Evaluate promise here and handle the response
}, function(error){
//handle error
});

Your function should be like this,
function getAll(page, size) {
return $http.get(baseUrl + '/jobprofiles?page='+page+'&size='+size, {timeout: 5000}).then(function (response) {
return data = response;
}, function(response) {
alertService.setAlert({'message': 'jobmatch.server.unavailable', 'classified': 'danger', 'lives':1});
});
}

Related

Issue with AngularJS promises within a factory

I have an angularjs factory like this:
'use strict';
angular.module('frontRplApp')
.factory('paymentService', function ($rootScope, $http, config, tools) {
var urlBase = config.baseUrl;
var paymentService = {
response: {},
create: function () {
var args = {};
return $http.post(urlBase + 'api/investor/payment/create', args);
}
});
And I intend to use it inside a controller like this (the important issue is being to do something different if all went well or if there was an error)
$scope.order = function () {
console.log('PaymentCashCtrl.order');
$scope.disabledButtons.submitCashOrder = true;
paymentService.create()
.then(
function (response) {
// do something with response
}, function (error) {
// do something with an error
}));
};
However my issue is that Id like to update some of the paymentService fields as the response of the $http.post is resolved and then return the promise so that the function(response) and function(error) callbacks in the controller keep working.
I tried with something like:
return $http.post(urlBase + 'api/investor/payment/create', args)
.then(function(response){
console.log(response);
this.response = response;
return response;
});
But it doesnt work since the function(error) handler in the controller is never called.
I want to use my handlers in the controller but also make some updates when the $http.post response is resolved.
Thanks.
in the factory, you need to return the functions paymentService object. also, don't resolve the promise inside the factory. resolve it in the controller.
.factory('paymentService', function($rootScope, $http, config, tools) {
var urlBase = config.baseUrl;
var paymentService = {
response: {},
create: function() {
var args = {};
return $http.post(urlBase + 'api/investor/payment/create', args);
}
}
return paymentService;
});
$scope.order = function() {
console.log('PaymentCashCtrl.order');
$scope.disabledButtons.submitCashOrder = true;
paymentService.create()
.then(
function(response) {
// do something with response
},
function(error) {
// do something with an error
}));
};
Use $q
Change your factory code to this:
angular.module('frontRplApp')
.factory('paymentService', function ($rootScope, $http, config, tools, $q) {
var urlBase = config.baseUrl;
var paymentService = {
response: {},
create: function () {
var deferred = $q.defer();
var args = {};
$http.post(urlBase + 'api/investor/payment/create', args)
.then(function(response){
console.log(response);
paymentService.response = response;
deferred.resolve(response);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
};
return paymentService;
});

Use output from services to controllers

I want to result of my $http.get from my service to my controller.
myserviceSample.js
function messagesService($q,$http){
var messages;
$http({
method: 'GET',
url: 'http://api.com/feedback/list'
})
.then(function success(response){
messages = response.data;
console.log(messages);
},function error(response){
console.log('error'+ response);
});
console.log(messages);
return {
loadAllItems : function() {
return $q.when(messages);
}
};
}
})();
mycontrollerSample.js
function MessagesController(messagesService) {
var vm = this;
vm.messages = [];
messagesService
.loadAllItems()
.then(function(messages) {
console.log(messages);
vm.messages = [].concat(messages);
});
}
})();
The above code results gives undefined output.
What i miss?
$q.when object does expect promise/object to make it working. In your case you have to pass promise object to $q.when as you are doing $http.get call. Here messages object doesn't hold promise of $http.get, so you could change the implementation of method like below.
Service
function messagesService($q,$http){
var messages = $http({
method: 'GET',
url: 'http://api.com/feedback/list'
})
.then(function success(response){
return response.data;
},function error(response){
return $q.reject('Error Occured.');
});
return {
loadAllItems : function() {
return $q.when(messages);
}
};
}
Then controller will resolve that promise & .then will do the trick
function MessagesController(messagesService) {
var vm = this;
vm.messages = [];
messagesService
.loadAllItems()
.then(function(messages) {
console.log(messages);
vm.messages = [].concat(messages);
});
}
Note: Using $q to create a custom promise, is considered as bad pattern when you have $http.get method there(which does return
promise itself)
Improved Implementation
function messagesService($q, $http) {
var messages, getList = function() {
return $http({
method: 'GET',
url: 'http://api.com/feedback/list'
})
.then(function success(response) {
messages = response.data
return response.data;
}, function error(response) {
return $q.reject('Error Occured.');
});
};
return {
loadAllItems: function() {
if (!data)
return getList(); //return promise
else
return $q.resolve(messages); //return data
}
};
};

Value of var goes back to empty after exiting function?

So I have an api request inside of a function thats placed in my Service script.. I have defined the variable "curruser" outside of the function so I can keep its value, however after exiting the follow Scirpt, curruser is empty??
services.js
function fbUserInfo() {
ngFB.api({
path: '/me',
params: {
fields: '/*params*/'
}
}).then(
function(user) {
curruser = user;
$http.get(/*send GET request to my server*/).success(function(response) {
if (response.length < 20) {
curruser.firsttime = true;
} else {
curruser.firsttime = false;
}
console.log(curruser);
console.log("1");
});
},
function(error) {
alert('Facebook error: ' + error.error_description);
});
}
So the console.log would return the proper JSON object I retrieved from facebook.. but when I return it in the return statement
return {
userInfo: function() {
fbUserInfo();
console.log(curruser);
return curruser;
}
it returns that curruser is an empty object! I did write
var curruser;
into the first line inside the ".factory"
you have to use then() since fbUserInfo() is async function
return {
userInfo: function() {
$.when(fbUserInfo())..then(
function(user) {
curruser = user;
$http.get(/*send GET request to my server*/).success(function(response) {
if (response.length < 20) {
curruser.firsttime = true;
} else {
curruser.firsttime = false;
}
console.log(curruser);
console.log("1");
});
},
function(error) {
alert('Facebook error: ' + error.error_description);
}).then(function(){
console.log(curruser);
return curruser;
})
}
Haven't tested this but might work.
var curruser;
function fbUserInfo( callback ) {
ngFB.api({
path: '/me',
params: {
fields: '/*params*/'
}
}).then(
function(user) {
curruser = user;
$http.get(/*send GET request to my server*/).success(function(response) {
if (response.length < 20) {
curruser.firsttime = true;
} else {
curruser.firsttime = false;
}
console.log(curruser);
console.log("1");
callback(curruser);
});
},
function(error) {
alert('Facebook error: ' + error.error_description);
});
}
return {
userInfo: function( callback ) {
fbUserInfo( function(data){
console.log(data);
callback(data);
});
}

Angularjs $http delete with $q promise leads to TypeError: object is not a function

The following snippet returns the following error: TypeError: object is not a function
service.deleteItem = function(itemId) {
var def = $q.defer();
$http.delete(SERVER_REST_PATH + '/items/' + itemId)
.success(function() {
def.resolve();
}).error(function(data, status) {
def.reject("Error deleting the item");
});
return def.promise();
};
If I rewrite it as the following it works:
service.deleteItem = function(itemId) {
return $http.delete(SERVER_REST_PATH + '/items/' + itemId);
};
All other $http methods that I use(i.e GET, PUT, POST) in my app are wrapped with the $q the same way and they don't have this issue. Only the DELETE is causing this issue. When I debug it it just skips the $http's success(), error() and then() methods. I'm using angular version 1.3.13.
change return def.promise(); to return def.promise;
example :
function deferredTimer(success) {
var deferred = $q.defer();
$timeout(function() {
if (success) {
deferred.resolve({ message: "This is great!" });
} else {
deferred.reject({ message: "Really bad" });
}
}, 1000);
return deferred.promise;
}

Using $http after previous $http done

I have 3 JSON web services which I should use in my application,
I use $http to load from URL, my code is :
$http.get('http://{url}/users')
.then(function (result) {
storeUsers(result);
});
$http.get('http://{url}/news')
.then(function (result) {
storeNews(result);
});
$http.get('http://{url}/pages')
.then(function (result) {
storePages(result);
});
var users = getUsers();
Problems :
1- all $http run together not wait until the previuse $http done.
2- var users = getUsers(); will run before $http done.
UPDATE :
I changed my code to :
var loadedService = {
users: false,
news: false,
pages: false
};
function getUsers() {
deferred = $q.defer();
$http.get('http://{url}/users')
.then(function (result) {
loadedService.users = result;
deferred.resolve('I got users');
console.log("Get users");
});
return deferred.promise;
}
function getNews() {
deferred = $q.defer();
$http.get('http://{url}/news')
.then(function (result) {
loadedService.news = result;
deferred.resolve('I got news');
console.log("Get news");
});
return deferred.promise;
}
function getPages() {
deferred = $q.defer();
$http.get('http://{url}/pages')
.then(function (result) {
loadedService.pages = result;
deferred.resolve('I got pages');
console.log("Get pages");
});
return deferred.promise;
}
getNews().then(getUsers()).then(getPages()).then(function () {
console.log('Done !');
});
When I run my program, I will see :
XHR finished loading: GET "http://{url}/pages". ionic.bundle.js:16185
Get pages sync.js:133
XHR finished loading: GET "http://{url}/users". ionic.bundle.js:16185
Get users sync.js:56
XHR finished loading: GET "http://{url}/news". ionic.bundle.js:16185
Get news sync.js:107
as you can see, first of all pages service loaded, then users service and then news, while in my code I said getNews().then(getUsers()).then(getPages()).
and finally console.log('Done !'); don't show !
You can use one of the ways MajoB or Muhammad suggested or you can have 3 functions that return promise and chain them in the order that you want.
function getUsers(){
deferred = $q.defer()
$http.get('http://{url}/users')
.success(function (result) {
storeUsers(result);
deferred.resolve('I got users')
}).error(function(data, status, headers, config) {
// called if an error occurs
console.log('error');
deferred.reject(status)
});
return deferred.promise
}
function getNews(){
deferred = $q.defer()
$http.get('http://{url}/news')
.success(function (result) {
storeUsers(result);
deferred.resolve('I got news')
}).error(function(data, status, headers, config) {
// called if an error occurs
console.log('error');
deferred.reject(status)
});
return deferred.promise
}
function getPages(){
deferred = $q.defer()
$http.get('http://{url}/pages')
.success(function (result) {
storePages(result);
deferred.resolve('I got pages')
}).error(function(data, status, headers, config) {
// called if an error occurs
console.log('error');
deferred.reject(status)
});;
return deferred.promise
}
For example lets say that you want to get the Pages after you get the News:
getNews().then(getPages())
Each even better to reject a promise on an error case and have an error handling on the chaining:
getNews().then(function() {
console.log('Success');
getPages();
}, function() {
console.log('Failed');
}, function() {
console.log('Executing... ');
});
Ofcourse the chain also returns a promise which you can handle.
you can chain your requests:
$http.get('http://{url}/users')
.then(function (result) {
storeUsers(result);
$http.get('http://{url}/news')
.then(function (newsResult) {
storeNews(newsResult);
$http.get('http://{url}/pages')
.then(function (pagesResult) {
storePages(pagesResult);
});
});
});
You can make $http requests run after each other by putting the code inside the success promise.
var users; // declare `users` variable
$http.get('http://{url}/users')
.then(function (result) {
storeUsers(result);
// second ajax request
$http.get('http://{url}/news')
.then(function (result) {
storeNews(result);
// third ajax request goes here
// .....
// set the value for users
users = getUsers();
});
});
here a little testScript for using promises with angularJs
$scope.myXhr = function(){
var deferred = $q.defer();
$http({
url: 'ajax.php',
method: "POST",
data:postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
//if request is successful
.success(function(data,status,headers,config){
//resolve the promise
deferred.resolve("request successful");
})
//if request is not successful
.error(function(data,status,headers,config){
//reject the promise
deferred.reject("ERROR");
});
//return the promise
return deferred.promise;
}
$scope.callXhrAsynchronous = function(){
var myPromise = $scope.myXhr();
// wait until the promise return resolve or eject
//"then" has 2 functions (resolveFunction, rejectFunction)
myPromise.then(function(resolve){
alert(resolve);
}, function(reject){
alert(reject)
});
}
You can try this:
NoticeService.observeReqUser().then(null,null,function(){
$http.get('http://{url}/users')
.then(function (result) {
storeUsers(result);
NoticeService.notifyStatusOne()
});
});
NoticeService.observeReqOne().then(null,null,function(){
$http.get('http://{url}/news')
.then(function (result) {
storeNews(result);
NoticeService.notifyStatusTwo()
});
});
NoticeService.observeReqTwo().then(null,null,function(){
$http.get('http://{url}/pages')
.then(function (result) {
storePages(result);
});
});
var users = getUsers();
You need to create a service to notify the request is done so the next one can be called
app.service('NoticeService',['$q',function($q){
var noticegetUserIsDone = $q.defer();
this.observeReqUser = function() { return noticegetUserIsDone.promise; };
this.notifyStatusUser = function() { noticegetUserIsDone.notify(); };
var noticeReqOneIsDone = $q.defer();
this.observeReqOne = function() { return noticegetUserIsDone.promise; };
this.notifyStatusOne = function() { noticegetUserIsDone.notify(); };
var noticeReqTwoIsDone = $q.defer();
this.observeReqTwo = function() { return noticegetUserIsDone.promise; };
this.notifyStatusTwo = function() { noticegetUserIsDone.notify(); };
};
You will need to call the NoticeService.notifyStatusUser from the end of getUser function so the chain will start to execute (Don't forget to add reference of the NoticeService where you call it)
You can use something like this, if I understand your question correctly:
$http.get('http://{url}/users')
.then(function (result) {
storeUsers(result);
return $http.get('http://{url}/news');
})
.then(function (result) {
storeNews(result);
return $http.get('http://{url}/pages');
})
.then(function (result) {
storePages(result);
users = getUsers();
});
$http.get will return promise.
Updated:
Or more clean solution:
var deferred = $q.defer(),
users;
$http.get('http://{url}/users')
.then(function (result) {
storeUsers(result);
return $http.get('http://{url}/news');
})
.then(function (result) {
storeNews(result);
return $http.get('http://{url}/pages');
})
.then(function (result) {
storePages(result);
deferred.resolve(result);
});
deferred.promise.then(function() {
users = getUsers();
});
Update2:
or more simple:
var request1 = $http.get('http://{url}/users'),
request2 = $http.get('http://{url}/news'),
request3 = $http.get('http://{url}/pages');
$q.all([request1, request2, request3]).then(function(result) {
storeUsers(result[0]);
storeNews(result[1]);
storePages(result[2]);
users = getUsers();
}
But you also need to handle rejection case.

Categories

Resources