Change template after login - angularjs

I'm trying to change the page after authentication but nothing happens unless I click again at the login button.
Here is the code :
myApp.controller('AuthController', ['$scope','$location', function($scope,$location) {
// (1) $location.path('/produtos');
$scope.email = '';
$scope.pass = '';
$scope.submit = function() {
var ref = new Firebase("https://myfirebasedb.firebaseio.com/");
ref.authWithPassword({
email : $scope.email,
password : $scope.pass
}, function(error, authData) {
if (error) {
console.log("Login failed !", error);
} else {
console.log("Login ok ! "); // (2)
$location.path('/produtos');
}
});
};
}]);
Below are the observations -
The commented instruction at (1) works ok
The message at (2) is correctly printed at the console
Thank you in advance.

Looks like something interrupts location change. Try setTimeout(function(){$location.path('/produtos');}, 0); - that helps in such situations.

Related

Event not waiting for user answer inside dialog

I need the user to confirm leaving the page if a specific condition is fulfilled. The problem is the location change is not waiting for the dialog to get the user answer.
Here's my code:
angular module 1:
...
function confirmLeavePage(e, newUrl) {
if(form.cod.value) {
customDialog.confirmDialog('Title','Leave?').then(
function(){
console.log('go to selected page');
},function(){
e.preventDefault();
});
}
}
$scope.$on("$locationChangeStart", confirmLeavePage);
...
angular module 2 :
angular.module('dialog').service('customDialog', function($mdDialog, $q, $location) {
this.confirmDialog = function(title, content){
var deferred = $q.defer();
$mdDialog.show($mdDialog.confirm({
templateUrl:'confirmDialog.html',
title : title,
textContent : content,
ok : 'Confirm',
cancel: 'Cancel'
})).then(function() {
console.log('confirmed');
deferred.resolve();
}, function() {
console.log('abort');
deferred.reject();
});
return deferred.promise;
}
});
Any ideas?
try this
function confirmLeavePage(e, newUrl) {
if(form.cod.value) {
customDialog.confirmDialog('Title','Leave?').then(
function(){
console.log('go to selected page');
});
}
e.preventDefault();
return;
}

facebook login using firebase in ionic

I am facing problem to get email and likes of user after facebook login using firebase into my ionic app.
Also after getting facebook display name and some other information in the user is not being redirected to the Dashboard page instead login page got refresh. Although i read different posts on stackoverflow and other sorces but i am stuck. Please help me to solve these two issues.
**1)**How to get email and likes of user
**2)**how to redirect user to dashboard soon after verified by facebook..
Here is the code
****Controller:****
$scope.loginFaceBook = function() {
///alert('fb Login firebase...');
var existingAuthData = Auth.$getAuth();
console.log("existingAuthData : ",existingAuthData);
//console.log("existingAuthData Email : ",existingAuthData.thirdPartyUserData.email);
Auth.$authWithOAuthRedirect("facebook").then(function(authData) {
alert('done 1');
// User successfully logged in
console.log(authData);
$location.path('app/Dash');
}, {
remember: "sessionOnly",
scope: "email,user_likes"
}).catch(function(error) {
if (error.code === "TRANSPORT_UNAVAILABLE") {
Auth.$authWithOAuthPopup("facebook").then(function(authData) {
// User successfully logged in. We can log to the console
// since we’re using a popup here
alert('done 2');
console.log(authData);
$location.path('app/Dash');
}, {
remember: "sessionOnly",
scope: "email,user_likes"
});
} else {
// Another error occurred
console.log(error);
alert('err');
}
});
Auth.$onAuth(function(authData) {
if (authData === null) {
console.log("Not logged in yet");
} else {
console.log("Logged in as", authData.uid);
console.log("Details",authData);
console.log("Name:",authData.facebook.displayName);
alert("Name:",authData.facebook.displayName);
console.log("gender:",authData.facebook.cachedUserProfile.gender);
console.log(" Email : ",authData.facebook.email);
$location.path('app/Dash');
}
$scope.authData = authData; // This will display the user's name in our view
});
};
**App.js**
// Ionic Starter App
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'ngCordovaOauth','firebase','ngFileUpload'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.factory("Auth", function($firebaseAuth) {
var usersRef = new Firebase("https//*********.firebase***.****/****");
return $firebaseAuth(usersRef);
})
Please make a constant to use it everywhere in your App like that
.constant('facebookUrl', 'https://rjrestaurantapp.firebaseio.com');
Then in the controller inject this constant "facebookUrl & "$state" as shown below
.controller('loginCtrl', function($scope,facebookUrl,$state){
and then you only need to give name of the state where you want to redirect after facebook authentication..
var ref = new Firebase(facebookUrl);
$scope.fbLogin = function () {
ref.authWithOAuthPopup("facebook", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
$state.go('restaurant');
}
})
}})
and for email and likes you have to first make sure that these information is shown in the object of authData after successfull authentication ..
please read this doc carefully https://www.firebase.com/docs/web/guide/login/facebook.html

Common service for sessionstorage in angularjs

Hi in my application i am setting the values in login controller and getting in all the other js files, other than this how to use a common service for setting storage and getting that storage in required js files
My login controller
app.controller('LoginController',function(loginService, $rootScope,$scope, $http,$location) {
$scope.login = function () {
$scope.log=loginService.getLogin( $scope.emailId , $scope.password).
then(function (response) {
console.log($scope.log);
console.log(response)
if (response.data.LoginVerificationResult.length === 0) {
alert('details are not Available for this emailId');
$scope.error=true;
} else {
$rootScope.name=response.data.LoginVerificationResult[0].UserName;
$scope.abc=response.data.LoginVerificationResult[0].UserType
console.log($scope.abc+"from.......");
sessionStorage.setItem("EmaiId",$scope.emailId);
sessionStorage.setItem("User Id",response.data.LoginVerificationResult[0].UserID);
sessionStorage.setItem("UserName",response.data.LoginVerificationResult[0].UserName);
sessionStorage.setItem("UserType",response.data.LoginVerificationResult[0].UserType);
$scope.UserType = sessionStorage.getItem("UserType");
console.log($scope.UserType +"from login controller")
$location.path('/dashboard')
}
});
};
});
My changepassword file
app.controller("ChangePwdController", function($scope, $http, $location,
BaseUrl, changePwdService) {
//$scope.roleId = sessionStorage.getItem("Role ID");
/* $scope.UserType = sessionStorage.getItem("UserType");*/
$scope.username = sessionStorage.getItem("UserName");
$scope.userType = sessionStorage.getItem("UserType");
$scope.EmpName=sessionStorage.getItem("EmpName");
$scope.patientName=sessionStorage.getItem("PatientName")
$scope.changePwd = function() {
$scope.emailAddress = sessionStorage.getItem("EmaiId");
console.log($scope.emailAddress)
var data = {
'emailAddress' : $scope.emailAddress,
'currentPassword' : $scope.opassword,
'newPassword' : $scope.npassword
};
console.log("Hi")
$scope.pwd=changePwdService.postChangePwd(data).success(
function(resp) {
$scope.PostDataResponse = data;
console.log($scope.pwd)
console.log($scope.PostDataResponse);
if (resp.ResetPasswordResult === true) {
alert("Successfully changed");
console.log("success")
$location.path('/dashboard');
} else {
console.log("fail")
alert("Enter valid current password")
}
})
}
})
Is there any alternative way to set and get in one file
There are ways in which you can achieve the same. Please refer this here.

iOS emulator GPS does not work?

I tested my app in the iOS emulator and noticed that the gps does not work.
In the emulator I set the location to "Apple"
and installed the corodova plugin by: "cordova plugin add org.apache.cordova.geolocation".
Here is my Code:
angular.module('home', ['services'])
.controller('homeCtrl',
function ($scope, $location, $state, serverAPI, $ionicPopup) {
$scope.buttonType = "icon ion-search";
$scope.buttonDisable = false;
$scope.text = 'Search';
var UID = JSON.parse(window.localStorage.getItem('Credentials')).UID;
serverAPI.getUserData(UID, function (data) {
$scope.userName = data.userName;
$scope.points = data.points;
$scope.fotoId = data.fotoId;
console.log(data);
});
$scope.click = function () {
$scope.buttonDisable = true;
$scope.text = 'Searching';
$scope.buttonType = 'icon ion-loading-a';
// //Grap geoLocation
var location = navigator.geolocation.getCurrentPosition(saveGeoData, onError);
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
};
var saveGeoData = function (geoData) {
console.log("nach geo");
var myPosition = {
'longitude': geoData.coords.longitude,
'latitude': geoData.coords.latitude
};
console.log("ss");
console.log(myPosition.latitude);
window.localStorage.setItem('myPosition', JSON.stringify(myPosition));
//If geoloaction is saved successfully => Send geodata to server to receive teammate
sendToServer(myPosition);
}
//Send current location to Server to receive teammate
var sendToServer = function (myPosition) {
serverAPI.searchPartnerToPlayWith(myPosition.longitude, myPosition.latitude, UID, function (data) {
//No other players around you. Server returns -1
if (data == -1) {
$ionicPopup.alert({
title: 'Too bad :(',
template: 'Unfortunateley there are no other players around you. Try it some other time!'
});
} else {
window.localStorage.setItem('teammate', data.username);
window.localStorage.setItem('isEnummeration', data.taskType);
window.localStorage.setItem('task', data.task);
var teammatePosition = {
'longitude': data.longitude,
'latitude': data.latitude
};
window.localStorage.setItem('teammatePosition', teammatePosition);
//TODO: data.fotoId => request foto from server
$state.go('tab.play-screen');
}
})
}
};
})
When the function click is called, it just stops in Line:
var location = navigator.geolocation.getCurrentPosition(saveGeoData, onError);
Do you have a guess whats my problem? In the browser it works just fine.
Thanks!
Make sure you include this file into your project.
https://github.com/apache/cordova-plugin-geolocation/blob/master/www/geolocation.js
It can be high probability cause from there, this function not exist in your project, getCurrentPosition.

Event loop Angular. Some functions not running on app initialisation until a button is clicked? -FIREBASE

Background:
I have the following setup to authenticate retrieve my user and then retrieve his credentials. I am unclear on the event loop even after reading the documentation.
The Question:
The user is not displayed until I click a button? Every other kind of function runs on initialization like the alerts and stuff but why is my retrieve user function working until another button is pressed (pressing any button )?
Summary:
In order to retrieve the username for some reason I need to click something. I want the username to be retrieve on initialization .
crossfitApp.controller('globalIdCtrl', ["$scope",'$q','defautProfileData','$timeout', function ($scope,$q,defautProfileData,$timeout) {
$timeout(function() {
var dataRef = new Firebase("https://glowing-fire-5401.firebaseIO.com");
$scope.myFbvar =null;
$scope.authenticated={
currentUser: null,
avatarUrl: "",
emailAddress: "",
settings: "",
currentUserid: null,
};
function getProfile(userID){
myprofile= new Firebase("https://glowing-fire-5401.firebaseio.com/profiles/"+userID+"/username");
myprofile.once('value', function(nameSnapshot) {
$scope.authenticated.currentUser = nameSnapshot.val();
});
};
$scope.auth = new FirebaseSimpleLogin(dataRef, function(error, user) {
if (error) {
//Error
console.log ('error');
}
else if (user) {
//logged in
$scope.$apply(function(){getProfile(user.id);})
console.log('logged in');
$scope.authenticated.currentUserid = user.id ;//
}
else {
// user is logged out
console.log('logged out');
$scope.authenticated.currentUserid =null;
$scope.authenticated.currentUserid =null;
}
});
},100);
}]); //GlobaldCtrl
I would move most of your code to a service, and call the service from your controller, like this. I also included a deferred object in your login as I bet this is async
crossfittpApp.service('firebase',function($q) {
return {
getUser : function(authenticated) {
var dataRef = new Firebase("https://glowing-fire-5401.firebaseIO.com"),
myFbvar =null,
getProfile(userID) {
myprofile= new Firebase("https://glowing-fire-5401.firebaseio.com/profiles/"+userID+"/username");
myprofile.once('value', function(nameSnapshot) {
authenticated.currentUser = nameSnapshot.val();
});
},
deferredObj = $q.defer();
auth;
auth = new FirebaseSimpleLogin(dataRef, function(error, user) {
if (error) {
//Error
console.log ('error');
deferObj.reject();
}
else if (user) {
//logged in
getProfile(user.id);
console.log('logged in');
authenticated.currentUserid = user.id ;
deferObj.resolve(auth);
}
else {
// user is logged out
console.log('logged out');
authenticated.currentUserid =null;
deferObj.resolve();
}
}
return deferObj.promise;
}
}
});
crossfittpApp.controller('globalIdCtrl',function(firebase) {
$scope.authenticated = {
currentUser: null,
avatarUrl: "",
emailAddress: "",
settings: "",
currentUserid: null,
};
firebase.getUser(authenticated)
.then(function(_auth) {
$scope.auth = _auth;
},
function() {
//auth error here
});
});
You're not triggering Angular's HTML Compiler, so Angular doesn't know you've changed the JS variables.
Whenever you use an event like ng-click/ng-submit/etc, Angular fires $scope.$apply(), which checks for any changes to your $scope variables and applies them to the DOM, which is why it shows up after this.
You can correct this issue by alerting Angular that it needs to run $apply by using $timeout:
angular.controller('MyController', function($timeout) {
myprofile= new Firebase("https://glowing-fire-5401.firebaseio.com/profiles/"+userID+"/username");
myprofile.once('value', function(nameSnapshot) {
$timeout(function() {
authenticated.currentUser = nameSnapshot.val();
});
});
auth = new FirebaseSimpleLogin(dataRef, function(error, user) {
if (error) {
//Error
console.log ('error');
}
else if (user) {
$timeout(function() {
authenticated.currentUserid = user.id ;
});
}
else {
$timeout(function(){
authenticated.currentUserid =null;
});
}
});
});
You should utilize angularFire, which abstracts these complexities.
There are some more questions like this one here, here, and here.

Resources