So this is a bit complex, but I'll try to get into it, the best I can. In my config.js, I have:
.run(['$rootScope', '$location', 'UserService', 'CompanyService', function($rootScope, $location, UserService, CompanyService) {
$rootScope.globals = {};
$rootScope.$on('login', function(event, data) {
$rootScope.api_key = data.api_key;
CompanyService.get(data.user.company_id);
});
UserService.checkAuth().then(function(response) {
if(response.data.user) {
// Logged in user
$rootScope.$broadcast('login', response.data);
} else {
UserService.logout();
}
});
}]);
which basically checks to see if a user is logged in. If he is, we find out which user he belongs to with the CompanyService:
angular.module('mean').service('CompanyService', ['$http', '$rootScope', function($http, $rootScope) {
var company = this;
company.company_data = {}
company.getCompany = function() {
return company.company_data;
}
company.get = function (company_id) {
return $http({
url: '/api/v1/company/' + company_id,
method: 'GET',
headers: {
api_key: $rootScope.api_key
}
}).success(function(response) {
if(response.status === 'ok') {
company.company_data = response.company;
}
});
};
}]);
Later on in my code, I have a call that relies on the singleton CompanyService to do an API call:
$scope.index = function() {
LocationService.get(CompanyService.getCompany()._id, $routeParams.location_parent_id).then(function(response) {
if(response.data.status === 'ok') {
$scope.locations = $scope.locations.concat(response.data.locations);
}
});
}
if I refresh the page, however, sometimes this call gets executed before we've put data in the CompanyService singleton. How can I use promises to make sure that the LocationService doesn't happen until after we have data in the CompanyService singleton?
One way to do this is without changing your existing code too much would be to create a promise that is fulfilled when CompanyService has data. Note that this code doesn't deal with errors so that still has to be added...
angular.module('mean').service('CompanyService',
['$http', '$rootScope', '$q', function ($http, $rootScope, $q) {
var company = this;
company.company_data = {}
var initializedDeferred = $q.defer;
company.initialized = initializedDeferred.promise;
company.getCompany = function () {
return company.company_data;
}
company.get = function (company_id) {
return $http({
url: '/api/v1/company/' + company_id,
method: 'GET',
headers: {
api_key: $rootScope.api_key
}
}).success(function (response) {
if (response.status === 'ok') {
company.company_data = response.company;
initializedDeferred.resolve(); // reject promise on error?
}
});
};
}]);
$scope.index = function () {
CompanyService.initialized.then(function () {
LocationService.get(CompanyService.getCompany()._id,
$routeParams.location_parent_id).then(function (response) {
if (response.data.status === 'ok') {
$scope.locations = $scope.locations
.concat(response.data.locations);
}
});
});
}
Related
Hi I am developing web application in angularjs. I have requirement below. I have one factory. I have added code snippet below.
myapp.factory('sadadpaymentapi', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', 'leaselisting', function ($http, $cookieStore, cfg, ScrollFunction, leaselisting) {
var sadadpaymentapiobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var urlapi = baseurl + "api/ServiceRequest/CreateRSSedad/";
sadadpaymentapiobject.callsadad = function (PaymentType) {
leaselisting.leaselisting().then(function (response) {
//Problem in calling
}, function (error) { });
var request = {
url: urlapi,
method: 'POST',
data: {
SRActivityID: LoginID,
PaymentType: PaymentType,
PaymentAmount: "100"
},
headers: ScrollFunction.getheaders()
};
return $http(request);
}
return sadadpaymentapiobject;
}]);
Here is my second factory leaselisting
myapp.factory('leaselisting', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', function ($http, $cookieStore, cfg, ScrollFunction) {
var leaselistingobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
leaselistingobject.leaselisting=function(){
var requestObj = {
url: "api/ServiceRequest/GetROLSPSRLeaseList/",
data: {
LoginID: LoginID,
RSAccountNumber: $cookieStore.get("AccountNumber")
},
headers: ScrollFunction.getheaders()
};
$http(requestObj).then(function (response) {
}, function (error) {
});
}
return leaselistingobject;
}]);
I have found error in below line
leaselisting.leaselisting().then(function (response) { //Problem in calling
}, function (error) { });
May i am i doing anything wrong in the above code? May i know is it possible to call one factory from another? The response i get from leaselisting i want to pass it in callsadad function of sadadpaymentapi. So can someone hep me in the above code? I am getting error Cannot read property 'then' of undefined in the leaselisting.leaselisting().then(function (response) {},function(error){});
Also is there any way I can directly inject factory like payment amount: inject factory something like this?
I assume, that leaselistingobject.getValue is an asynchronous function.
So first of get your value :
leaselistingobject.getValue = function(){
var requestObj = {
url: "api/ServiceRequest/getValue/"
};
return $http(requestObj).then(function (response) {
return response.data;
});
}
And then use it. To let all async actions finish we use angulars $q.Here you can find a small tutorial.
myapp.factory('sadadpaymentapi', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', 'leaselisting', '$q',function ($http, $cookieStore, cfg, ScrollFunction, leaselisting, $q) {
var sadadpaymentapiobject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var urlapi = baseurl + "api/ServiceRequest/CreateRSSedad/";
sadadpaymentapiobject.callsadad = function (PaymentType) {
var leastListingPromise = leaselisting.leaselisting();
var getValuePromise = leaselisting.getValue();
$q.all([leastListingPromise, getValuePromise]).then(function (responses) {
//Here you have both responses in an array
var request = {
url: urlapi,
method: 'POST',
data: {
SRActivityID: LoginID,
PaymentType: PaymentType,
PaymentAmount: responses[1]
},
headers: ScrollFunction.getheaders()
};
return $http(request);
});
}
return sadadpaymentapiobject;
}]);
To make leaselisting() return the response of the request change the end of the function from
$http(requestObj).then(function (response) {
}, function (error) {
});
to
return $http(requestObj).then(function (response) {
return response.data;
}, function (error) {
});
If wont do anything about possible errors you can omit the error function part:
return $http(requestObj).then(function (response) {
return response.data;
});
I'm having trouble running a function from a service, because it is being called twice.
I've noticed that most of the problems of this nature are because people tend to call their controller twice (one time in the router and another in the view with ng-controller). But I checked, and my controller is not being invoked twice. Also: only on function from the service is being called twice.
Here it is:
.factory('findingsService', ['$http', '$log', '$q', '$cookies', function ($http, $log, $q, $cookies) {
return {
// THIS FUNCTION IS WORKING FINE!
list_findings: function(examId) {
var defer = $q.defer();
var session_token = $cookies.get('ACCESS_TOKEN');
$http.get(WS + URI_FINDINGS, {
headers: {
'sessionToken': session_token,
'Content-Type': 'application/json'
},
params: {
'examId': examId
}
})
.then(function (response) {
defer.resolve(response.data);
})
.catch(function (data) {
defer.reject(data);
});
return defer.promise;
},
// THIS FUNCTION IS BEING CALLED TWICE
attach_findings_to_exam: function(examId, findingsObj) {
var defer = $q.defer();
var session_token = $cookies.get('ACCESS_TOKEN');
$http.post(WS + URI_FINDINGS, findingsObj, {
headers: {
'sessionToken': session_token,
'Content-Type': 'application/json'
},
params: {
'examId': examId
}
})
.then(function (response) {
defer.resolve(response.data);
})
.catch(function (data) {
defer.reject(data);
});
return defer.promise;
}
}
}])
Since it's the same service and only one function is being called twice, and think that discarding the controller issue is fine. Can it be something about the global configuration of the $http.post?
I am binding translation.
The issue is , some object convert to translated value, while some like mentioned below didn't work. This issue happened only first time when I build project. On refresh it gets fine.
This is not happening to all html objects.
angular.module('App').factory('APILoader', ['localStorageService', '$http', '$q', function (localStorageService, $http, $q) {
var translationAPIUrl = "Translation/Get";
return function (options) {
var deferred = $q.defer();
$http.get(translationAPIUrl, { params: { id: culture } }).success(function (response) {
data = JSON.parse(response.data);
deferred.resolve(data);
}).error(function (data) {
deferred.reject(options.key);
});
return deferred.promise;
};
}]);
Html:
<b> {{('Heading' |translate)}}</b>
I got it.
The issue is with deferred,
It did not resolve properly and get return.
The Key line is:
deferred.promise.then(function () {});
Here is the fixed code:
angular.module('App').factory('APILoader', ['localStorageService', '$http', '$q', function (localStorageService, $http, $q) {
var translationAPIUrl = "Translation/Get";
return function (options) {
var deferred = $q.defer();
$http.get(translationAPIUrl, { params: { id: culture } }).success(function (response) {
data = JSON.parse(response.data);
deferred.resolve(data);
deferred.promise.then(function () {});
});
}).error(function (data) {
deferred.reject(options.key);
});
return deferred.promise;
};
}]);
I wrote a factory to long-poll, with start and stop methods. However, I can't cancel the timer. Any ideas?
app.controller("AuthCtrl", function($scope, $http, $window, User, Poller) {
Poller.start(1, $scope.session.user.user_uuid, function(result) {
User.data.queues.montage_progress = result.field;
if (result.field == 100) {
Poller.stop(); //DOES NOT STOP (see below)
}
});
})
Here is the factory:
app.factory('Poller', function($http, $q, $interval, $window) {
var poll = this;
poll.timer = null;
poll.checkProgress = function(field, user_uuid) {
var deferred = $q.defer();
$http({
method: 'GET',
url: '/api/v1/poll/',
json: true,
params: {
field: field,
user_uuid: user_uuid
}
})
.success(function(data) {
deferred.resolve(data);
}).error(function() {
deferred.reject("Error checking poll");
});
return deferred.promise;
};
poll.start = function(url, user_uuid, callback) {
poll.timer = $interval(function() {
poll.checkProgress(url, user_uuid).then(function(result) {
console.log(result);
callback(result);
}, function(error) {
alert(error);
});
}, 2000);
};
poll.stop = function() {
$interval.cancel(poll.timer);
};
return poll;
});
EDIT:
Changed $window.clearInterval to $interval.cancel(poll.timer); as suggested below. But still can't cancel polling...
You should use the cancel method of $interval, not clearInterval
poll.stop = function() {
$interval.cancel(poll.timer):
};
I have the following code in the controller.js,
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
$http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
return data
}).error(function(){
alert("error");
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = dataService.getData();
});
But, I think I m probably making a mistake with CORS related issue. Can you please point me to the correct way to make this call? Thanks much!
First, your success() handler just returns the data, but that's not returned to the caller of getData() since it's already in a callback. $http is an asynchronous call that returns a $promise, so you have to register a callback for when the data is available.
I'd recommend looking up Promises and the $q library in AngularJS since they're the best way to pass around asynchronous calls between services.
For simplicity, here's your same code re-written with a function callback provided by the calling controller:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function(callbackFunc) {
$http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
// With the data succesfully returned, call our callback
callbackFunc(data);
}).error(function(){
alert("error");
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData(function(dataResponse) {
$scope.data = dataResponse;
});
});
Now, $http actually already returns a $promise, so this can be re-written:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
// $http() returns a $promise that we can add handlers with .then()
return $http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(dataResponse) {
$scope.data = dataResponse;
});
});
Finally, there's better ways to configure the $http service to handle the headers for you using config() to setup the $httpProvider. Checkout the $http documentation for examples.
I suggest you use Promise
myApp.service('dataService', function($http,$q) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
deferred = $q.defer();
$http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
// With the data succesfully returned, we can resolve promise and we can access it in controller
deferred.resolve();
}).error(function(){
alert("error");
//let the function caller know the error
deferred.reject(error);
});
return deferred.promise;
}
});
so In your controller you can use the method
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(response) {
$scope.data = response;
});
});
promises are powerful feature of angularjs and it is convenient special if you want to avoid nesting callbacks.
No need to promise with $http, i use it just with two returns :
myApp.service('dataService', function($http) {
this.getData = function() {
return $http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
return data;
}).error(function(){
alert("error");
return null ;
});
}
});
In controller
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(response) {
$scope.data = response;
});
});
Try this
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
Just setting useXDomain = true is not enough. AJAX request are also send with the X-Requested-With header, which indicate them as being AJAX. Removing the header is necessary, so the server is not rejecting the incoming request.
So you need to use what we call promise. Read how angular handles it here, https://docs.angularjs.org/api/ng/service/$q. Turns our $http support promises inherently so in your case we'll do something like this,
(function() {
"use strict";
var serviceCallJson = function($http) {
this.getCustomers = function() {
// http method anyways returns promise so you can catch it in calling function
return $http({
method : 'get',
url : '../viewersData/userPwdPair.json'
});
}
}
var validateIn = function (serviceCallJson, $q) {
this.called = function(username, password) {
var deferred = $q.defer();
serviceCallJson.getCustomers().then(
function( returnedData ) {
console.log(returnedData); // you should get output here this is a success handler
var i = 0;
angular.forEach(returnedData, function(value, key){
while (i < 10) {
if(value[i].username == username) {
if(value[i].password == password) {
alert("Logged In");
}
}
i = i + 1;
}
});
},
function() {
// this is error handler
}
);
return deferred.promise;
}
}
angular.module('assignment1App')
.service ('serviceCallJson', serviceCallJson)
angular.module('assignment1App')
.service ('validateIn', ['serviceCallJson', validateIn])
}())
Using Google Finance as an example to retrieve the ticker's last close price and the updated date & time. You may visit YouTiming.com for the run-time execution.
The service:
MyApp.service('getData',
[
'$http',
function($http) {
this.getQuote = function(ticker) {
var _url = 'https://www.google.com/finance/info?q=' + ticker;
return $http.get(_url); //Simply return the promise to the caller
};
}
]
);
The controller:
MyApp.controller('StockREST',
[
'$scope',
'getData', //<-- the service above
function($scope, getData) {
var getQuote = function(symbol) {
getData.getQuote(symbol)
.success(function(response, status, headers, config) {
var _data = response.substring(4, response.length);
var _json = JSON.parse(_data);
$scope.stockQuoteData = _json[0];
// ticker: $scope.stockQuoteData.t
// last price: $scope.stockQuoteData.l
// last updated time: $scope.stockQuoteData.ltt, such as "7:59PM EDT"
// last updated date & time: $scope.stockQuoteData.lt, such as "Sep 29, 7:59PM EDT"
})
.error(function(response, status, headers, config) {
console.log('### Error: in retrieving Google Finance stock quote, ticker = ' + symbol);
});
};
getQuote($scope.ticker.tick.name); //Initialize
$scope.getQuote = getQuote; //as defined above
}
]
);
The HTML:
<span>{{stockQuoteData.l}}, {{stockQuoteData.lt}}</span>
At the top of YouTiming.com home page, I have placed the notes for how to disable the CORS policy on Chrome and Safari.
When calling a promise defined in a service or in a factory make sure to use service as I could not get response from a promise defined in a factory. This is how I call a promise defined in a service.
myApp.service('serverOperations', function($http) {
this.get_data = function(user) {
return $http.post('http://localhost/serverOperations.php?action=get_data', user);
};
})
myApp.controller('loginCtrl', function($http, $q, serverOperations, user) {
serverOperations.get_data(user)
.then( function(response) {
console.log(response.data);
}
);
})