I try to implement a remember-login function to my AngularJS / ionic mobile app
the problem:
the login page is allways loaded before the automatic login is finished and the transition starts, so you can see the login page for a moment.
question:
is there an event like 'pagebeforeshow' in JQM or another method to directly load the 'home' state?
I use:
ionic 1.3.1
angular 1.5.3
cordova 4.0.0
code examples:
LoginController:
function LoginController($scope, $http, $ionicModal, $state, $SessionStorage) {
var vm = this;
activate();
function activate(){
vm.staylogged = JSON.parse(localStorage.staylogged || null);
if(vm.staylogged){
vm.remember = vm.staylogged; //vm.remember: checkbox in login form
login();
}else{
// get some data from the server
}
}
function login(){
if(vm.staylogged){
//get login informations from localStorage
}
$http({
method: 'POST',
url: vm.server +"?=GetLogin",
headers: {
'Content-Type': 'text/xml; charset=\"utf-8\"'
},
data: soa
}).then(function successCallback(response) {
if(response.returnCode == 0){
localStorage.setItem('staylogged', JSON.stringify(vm.remember));
// safe login informations to local Storage for next use
$state.go('tabs.home');
}
}, function errorCallback(response) {
console.log(response);
});
}
}
You can do following way -
In app.js
.state('signin', {
url: '/sign-in',
templateUrl: 'templates/views/login.html',
controller: 'LoginController',
resolve: {
// Do your code here will execute before page render
}
})
Related
I created a http post request using an api and now I am having a minor issue. once I logout of the form, I can still access the home page without putting login details. the session does not expire even after logout. here is the code I am using in my login controller:
var app = angular.module('LoginApp');
app.controller('loginController', function($scope,$http,$rootScope,$window) {
$scope.postdata = function () {
var post = $http({
method: "POST",
url: "https://api-stg.martcart.pk/api/v1/user/login",
dataType: 'json',
data: JSON.stringify({
userName: $scope.username,
password: $scope.password
}),
headers: { "Content-Type": "application/json" }
});
post.success(function (data) {
window.location='components/home/home.html';
sessionStorage.setItem("authdata",JSON.stringify(data.token));
});
post.error(function () {
alert("wrong credentials");
});
}
$scope.logout = function(){
// console.log("hello")
window.location.href = 'http://localhost:5500/LoginAngularJS-API-master/index.html#/login';
$window.sessionStorage.removeItem("authdata");
//localStorage.removeItem("authdata");
// $route.reload();
// delete $window.sessionStorage;
// $window.localStorage.clear();
}
});
the logout.js function being called once logout button is clicked:
function logout() {
window.location.href = 'http://127.0.0.1:5500/LoginAngularJS-API-master/index.html#/login';
sessionStorage.removeItem("authdata");
// sessionStorage.destroy();
// localStorage.removeItem("authdata");
// delete $window.sessionStorage;
// $window.localStorage.clear();
}
will e glad if anyone could help trouble shoot the issue.
Thanks alot
Your code looks fine time. Maybe try sessionStorage.removeItem("authdata");
without the $window.
I have ng-click button when I click on it, I run an ajax call like the following:
function Click(data){
var obj = {'data':data};
return $http({
method: "POST",
url:("x.php"),
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({data:obj}),
})
.then(complete)
.catch(function(message) {
throw new Error("XHR Failed ",message);
});
function complete(data, status, headers, config) {
}
}
then I am trying to navigate to another route while the ajax call is still running and I get a message:
Do you want to leave the site?
I don't want pop up like that at all.
I tried to put window.onbeforeunload = null; in each page but it is not working
How can I disable it?
Also, sometime I get a refresh popup.
My routing:
// Optimize load start with remove binding information inside the DOM element
$compileProvider.debugInfoEnabled(true);
// Set default state
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url: "/",
templateUrl: "x.php",
controller: 'xController',
controllerAs: 'vm',
resolve: {
fun: function(x) {
return x.get();
}
}
});
$httpProvider.interceptors.push('saHttpActivityInterceptor');
I want to keep user login status even refresh the browser. But I find a problem when I apply $cookies in angularjs. Following is my code:
function signIn() {
var params = {email: vm.email, password: vm.password};
Service.authBuffer = _.extend(Service.authBuffer, params);
$.ajax({
type: 'POST',
url: GetEndpointUrl('/api/auth/login'),
dataType: "jsonp",
data: params,
success: function(data) {
console.log("login data", data);
$scope.safeApply(function() {
Service.authBuffer = _.extend(Service.authBuffer, data);
console.log("login auth data", Service.authBuffer);
$location.path('/task');
var cookieExp = new Date();
cookieExp.setDate(cookieExp.getDate() + 7);
$cookies.put('Service.authBuffer', Service.authBuffer.email, { expires: cookieExp });
})
}
})
}
So I am wondering how to change the code to make $cookies work.
You probably have not injected the ngCookies module. Use something like this
angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Retrieving a cookie
var favoriteCookie = $cookies.get('myFavorite');
// Setting a cookie
$cookies.put('myFavorite', 'oatmeal');
}]);
Reference Link
Answer few of this questions to get better understanding of the problem:
- please provide the error message you get in console log of browser
- have you included angular-cookies library?
- have you injected ngCookies in app module?
- have you injected $cookies in controller?
I have a requirement like to get the data before loading the page by using angular js providers ,am not implement it please anybody help me.
This is my code please go through it
hiregridApp.provider('organizationService', function() {
return {
getOrganization: ['$http', '$location',
function($http, $location) {
$http({
method: 'GET',
url: http: //dev.api.hiregrid.io/api/customer/token/hiregrid',
}).success(function(data) {
$log.log(data);
}).error(function(error, status) {
$routeParams.code = status;
$location.path('/error/' + $routeParams.code);
});
}
]
}, this.$get: ['$http', '$location',
function($http, $location) {
var obj = '';
alert("hai");
obj.getOrganization = function() {
$http({
method: 'GET',
url: 'http://dev.api.hiregrid.io/csbuilder- api/api/csbuilder/hiregrid',
}).success(function(data) {
$log.log(data);
}).error(function(error, status) {
$routeParams.code = status;
$location.path('/error/' + $routeParams.code);
});
return obj;
}
}
];
});
hiregridApp.config(function(organizationServiceProvider) {
console.log(organizationServiceProvider);
organizationServiceProvider.getOrganization("http://dev.api.hiregrid.io");
});
You could resolve your data in routing so when ever you navigate to a page it will resolve your data and then navigate.
Note if server take long time to response so it will not navigate u till it has resolved your promise.
You can use your provider in config where you have your router configuration.
angular.module ('app',[]).config (function(yourProvider){})
var config = { headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;'}};
App.provider('organizationService', ['$http',
function($http) {
return {
getOrganization: function (){
$http.get("http: //dev.api.hiregrid.io/api/customer/token/hiregrid",config)
.success(function(data) {
$log.log(data);
}).error(function(error, status) {
$routeParams.code = status;
$location.path('/error/' + $routeParams.code);
});
}
}
}
]);
If you want to load data before page loaded, use resolve inside your router. For that you don't need providers.
About resolve you can read here angular router
I wrote a controller for login page. Here is my controller:
var authApp = angular.module('loginApp', [])
authApp.controller('LoginCtrl', ['$scope', '$location', 'loginFactory', function($scope, $location, loginFactory){
$scope.authenticate = function() {
loginFactory.login($scope.username, $scope.password)
.then(function(response) {
console.log(response.$statusText);
}, function errorCallBack(response) {
console.log(response.$statusText);
});
}
}]);
My service:
authApp.factory("loginFactory", function ($http) {
return{
login: function(username, password) {
var data = "username="+username+"&password="+password+"&submit=Login";
return $http({
method: 'POST',
url: 'http://localhost:8080/login',
data: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
});
}
When I debug the code, authentication seems successful and it did get into then function. However nothing displays in console. And I got a warning(?) saying undefined for the line console.log(response.$statusText);. It is not an error since it is not red. Why doesn't it print out anything?
Use response.statusText not response.$statusText. The documentation for AngularJS $http requests lists statusText as one of the properties of the response object - https://docs.angularjs.org/api/ng/service/$http