angularjs service doesn't work fine when call for API? - javascript

I was working with a angular project that include controllers and services. problem comes out from the codes following:
qrcodeCtrl.js
angular
.module('Admin',['ngResource'])
.controller('qrcodeCtrl',function($scope,qrcodeservice,statusservice){
$scope.init = function(){
$scope.getQrcodes();
}
$scope.getQrcodes = function(){
qrcodeservice.getQrcodes()
.then(function(res){
$scope.qrcodes = qrcodeservice.qrcodeList;
$scope.loginstatus = [];
var logininfo = [];
for(var i = 0; i < $scope.qrcodes.length; i++){
logininfo[i] = self.setInterval(getloginfo,10000,i);
}
function getloginfo(i){
uuid = $scope.qrcodes[i];
statusservice.getstatus(uuid).then(function (result) {
console.log(uuid+" "+result.code);
uuid = result.uuid;
switch(result.code){
case 201 : $scope.loginstatus[uuid] = 'login ...';break;
case 200 : $scope.loginstatus[uuid] = 'login success';window.clearInterval(logininfo[i]);break;
case 500 : $scope.loginstatus[uuid] = 'login fail';window.clearInterval(logininfo[i]);break;
default : $scope.loginstatus[uuid] = 'waitting';break; //code 408
}
},function (err) {
console.log(err);
})
return;
}
},function(err){
console.log(err);
})
}
$scope.init();
})
statuservice.js
angular
.module('Admin',['ngResource'])
.service('statusservice',function ($http,$q) {
var auth = this;
auth.getstatus = function(uuid){
var defer = $q.defer();
// //debug
// var code = 200;
// var result = {"uuid":uuid,"code":code};
// defer.resolve(result);
// return defer.promise;
// //=================
$http.get("/check?uuid="+uuid)
.success(function(code){
res = {"uuid":uuid,"code":code};
defer.resolve(res);
})
.error(function(err,status){
console.log(err);
defer.reject(err);
})
return defer.promise;
}
})
about the codes, the service is for getting login info from API which test work fine. and the controller set a interval for getting login info from service constantly. When it turn out login success(200) or login fail (500), the interval will stop. those codes work for login section of a project.
When service doesn't get the login code from API and just write the code, (comment section)the service work fine , the code is 200 and the interval stop, alse view render fine.
But when service get the login code from API, the interval doesn't stop. and from the chrome console , i find out that the code is success change to 200, but still loop the interval. and the view doesn't render to login success.
I was learning angular for few days, could someone tell me why that happen??

your module declaration and usage is incorrect
angular.module('Admin',['ngResource']).something should not be done;
this initialize module admin every time.
you should declare in the below format
var app = angular.module('Admin',['ngResource']);
angular
.module('Admin')
.service('statusservice',function ($http,$q) {
});
angular
.module('Admin')
.controller('qrcodeCtrl',function($scope,qrcodeservice,statusservice){
});

Related

Angular 5 + OAuth2: Token not getting set with libary [angular-oauth2-oidc]

I am trying to configure my Angular app to use the OAuth2 library (angular-oauth2-oidc).
In the file auth.service.ts my OAuthService is configured:
this.oauthService.loginUrl = 'https://serverdomain.com/authorization/';
this.oauthService.redirectUri = 'http://localhost:4200/auth';
this.oauthService.clientId = '1111-2222-3333-4444-5555-6666-7777';
this.oauthService.setStorage(localStorage);
this.oauthService.requireHttps = false;
this.oauthService.responseType = 'token';
this.oauthService.tokenEndpoint = 'https://serverdomain.com/token/';
this.oauthService.oidc = false;
this.oauthService.issuer = 'https://serverdomain.com/authorization/';
this.oauthService.tokenValidationHandler = new JwksValidationHandler();
this.oauthService.requestAccessToken = true;
this.oauthService.showDebugInformation = true;
this.oauthService.scope = 'openid profile email';
this.oauthService.tryLogin({
onTokenReceived: context => {
console.log(context);
}
});
obtainAccessToken() {
this.oauthService.initImplicitFlow();
}
isLoggedIn() {
if (this.oauthService.getAccessToken() === null) {
return false;
}
return true;
}
logout() {
this.oauthService.logOut();
location.reload();
}
logAuthData() {
console.log(this.oauthService.hasValidAccessToken());
}
In my home component I added a button to trigger the implicit flow and get an access token.
After initialization of the implicit flow the app redirects to the correct login page of the provider where I log in and get redirected to my redirectUri of my OAuth configuration.
BUT
If I try to get a state, for example I call isLoggedIn method, I get always false. Also, there is a false return at hasValidAccessToken().
Can anybody show how to correctly configure angular 5 and oauth2?
I need also a possibility to store my given access token to use them in my rest methods to get data.
Need to add JWKs token Validator in your configration. And set Jwks as per your Response type
this.oauthService.tokenValidationHandler = new JwksValidationHandler();

how to store login info with angularJS

I am currently develloping a little app with angularJS;
the users have to go through a login form and then they can click on a few links who display data fetched from a server.
The login form only takes the user's input and it is then "stored" into a factory
app.factory('IdFormHolder', function () {
var that = this;
that.setId = function (data) {
that = data;
};
that.getId = function () {
return that;
};
return that;
});
Which works fine I need to keep it stored because the server requires the login form to be sent each time I do a $http.get as a header.
Each controller takes the login form from the factory and uses it to get the data from the server.
This works fine until someone decides to refresh the page, at which point it seems the factory is "emptied" from its login form, and the web-app then fails to show anything.
Is there a way to store this login info so that it doesn't get erased so easily ?
You can use this code after youve installed sessionStorage:
app.factory('IdFormHolder', ['$sessionStorage', function ($sessionStorage) {
var that = this;
that.setId = function (data) {
$sessionStorage.id = data;
that = data;
};
that.getId = function () {
return $sessionStorage.id;
};
return that;
}]);
Download Link: https://github.com/gsklee/ngStorage
In order to persist data you'd have to use some kind of local DB || LocalStorage || SessionStorage at least. When initializing the Factory you could check and attempt to retrieve from DB/LS that data and hold it as a variable if it does exist.
Something like
app.factory('IdFormHolder', function () {
this.heldId = attemptToGetSavedDataFromSomewhere(); // would be null otherwise
this.setId = (id) => {
this.heldId = id;
};
this.getId = () => this.heldId;
return this;
});
Using angular-local-storage you can access to the browsers local storage:
app.factory('IdFormHolder', function(localStorageService) {
return {
setId: function(data) {
return localStorageService.set('loggedUserData', data);
},
getId: function() {
return localStorageService.get('loggedUserData');
}
};
});

Google API JavaScript Client - Quota Error: User Rate Limit Exceeded

I'm building a web app that that is going to perform certain tasks on our Google Analytics account but i'm getting errors due to 'userRateLimitExceeded'.
What I have at the moment:
(1) Run normal (unbatched) query for the management account list.
(2) Run a second query, batched, for all web properties on each account.
The first query runs as expected, the second batch query completes but every sub query has the same error 'Quota Error: User Rate Limit Exceeded.'.
From my understanding the client library implements a rate limiting mechanism which ensures this doesn't happen. Can anyone explain whats happening to help resolve this issue, highly likely I am doing something wrong. Thanks up front for any help you can give.
(function(window){
"use strict";
var dataStore = new GlobalDataStore();
function handleAccountProperties(AccountProperties){
console.log(AccountProperties);
}
function getAccountProperties(){
var batch = gapi.client.newBatch();
for (var i = 0; i < dataStore.accounts.length; i++) {
var account = dataStore.accounts[0];
var request = gapi.client.analytics.management.webproperties.list({
'accountId': account.details.id
});
batch.add(request);
}
batch.then(function(response){
handleAccountProperties(response.result);
}, function(reason){
console.log('Error: ' + reason.result.error.message);
});
};
function getAndHandleAccounts(){
var request = gapi.client.analytics.management.accounts.list();
request.then(function(response) {
if(response.result.items && response.result.items.length) {
for (var i = 0; i < response.result.items.length; i++) {
var account = new GoogleAnalyticsAccount();
account.details = response.result.items[i];
dataStore.accounts.push(account);
}
getAccountProperties();
}
});
};
function authorise(){
var authData = {
client_id: dataStore.clientID,
scope: dataStore.scopes,
immediate: false
};
gapi.auth.authorize(authData, function(response) {
if (response.error) {
console.error('shit went wrong');
} else {
gapi.client.load('analytics', 'v3').then(getAndHandleAccounts);
}
});
};
window.onload = authorise;
})(window);

AngularJS - Improving service call and data binding performance

I have an Angular service that goes away to retrieve a pretty big JSON file (nearly 10,000 lines).
The problem i am facing, is that it is taking some time to bind the data to the front-end (as expected).
Sample controller:
$scope.dataLoaded = false;
serviceReport.getData( function (data) {
$scope.data1 = data.data1;
$scope.data2 = data.data2;
$scope.data3 = data.data3;
$scope.data4 = data.data4;
$scope.data5 = data.data5;
$scope.data6 = data.data6;
$scope.data7 = data.data7;
$scope.data8 = data.data8;
$scope.data9 = data.data9;
$scope.data10 = data.data10;
$scope.data11 = data.data11;
$scope.data12 = data.data12;
$scope.data13 = data.data13;
$scope.data14 = data.data14;
$scope.data15 = data.data15;
$scope.data16 = data.data16;
$scope.data17 = data.data17;
$scope.dataLoaded = true;
});
Service:
app.factory('serviceReport', function($http) {
return {
getData: function(value,done) {
$http.get('data.json', {
})
.success(function(data) {
done(data);
})
.error(function(error) {
alert('An error occured');
});
}
}
});
I have ng-cloak on my HTML element, when dataLoaded = true, this is removed as it indicates the data is available to be displayed.
How can i improve the service call/data bind? Would splitting the call help?
Server-side solution would be to reduce the size of the response and make more requests with smaller responses. Do you actually need the whole response at start? You have to be aware that binding the whole response will generate many watchers, which will slow down all subsequent digests.
Client-side solution would be to bind the response part by part in a loop as a callback parameter for $scope.$apply() or even $timeout().

Internet explorer 11 Angularjs + NodeJS + Mongoose issue

I'm developping my website with Angularjs framework in the front end , nodejs backend and mongoose to persist my data into a MongoDB database.
In firefox RS v.24 and chrome all is ok, when i add a user into the database, this new user is displayed automatically into my list grid.
But in IE 11 it doesn't until i close the browser and open it back .
when i add a new profile, i do the following in my Controller:
$scope.AddProfil = function() {
$http.post('/ajouterProfils', $scope.profil)
.success(function(data) {
$scope.profilFlag = data; /*unit tests*/
$scope.lastDocId = data._id;
$scope.ajouterProfilTag($scope.lastDocId);
$scope.profil = {};
$scope.tagStyles.length = 0;
$scope.tagStyles = [];
$scope.colorList = {};
angular.element($('.shown-text-add').text($('.shown-text-add').text()));
angular.element($('.shown-text-add').css('font-family', ''));
angular.element($('.shown-text-add').css('font-size', ''));
angular.element($('.shown-text-add').css('line-height', ''));
angular.element($('.shown-text-add').css('font-weight', ''));
setTimeout( function(){$('#addPanel').show();} );
setTimeout( function(){$('#addPanel').fadeOut();}, 2500);
});
};
in my DAO, i have this :
/**
* Add a profile
*/
exports.createProfile = function(req, res) {
var profile = new Profil(req.body);
profile.save(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
profile: profile
});
} else {
res.jsonp(profile);
}
});
};
Any ideas ? feedbacks ?
As commented, use directives and data binding rather than DOM manipulation.
Clearly this is your problem as you say the data is there when you reload the browser, so the issue is not with the server side components.

Categories

Resources