problem while using local storage in ionic - ionic-framework

What i am trying to do-
i am setting (again) some key (which are set at some other point in my application i.e, Login )value pairs in local storage when a function is called.
similar to reset password.
and it works fine just the problem is that when on the same page if i access those items after resetting them it shows undefined. but when i do login again those values are changed and shows the latest values.
i also tried running on android device and in ionic serve and ionic lab . it never worked.
constructor(public navCtrl: NavController,
public navParams: NavParams,
public apiConnect:ApiIntegrationProvider,
public loadingCtrl:LoadingController,
public toastCtrl:ToastController,
public storage: Storage) {
console.log(this.user_name)
this.fetchProfile();
}
fetchProfile(){
this.user_role=localStorage.getItem("userRole");
this.user_name=localStorage.getItem("userName");
this.user_Email=localStorage.getItem("userEmail");
this.user_Mobile=localStorage.getItem("userMobile");
this.user_Avatar=localStorage.getItem("userAvatar");
this.user_Language=localStorage.getItem("userLanguage");
this.company_name=localStorage.getItem("companyName");
this.company_email=localStorage.getItem("companyEmail");
this.company_punch=localStorage.getItem("companyPunch");
this.company_url=localStorage.getItem("companyUrl");
console.log("user data")
console.log("company name", this.company_name,"email",this.company_email,"punch",this.company_punch,"website", this.company_url,"language", this.user_Language);
if(this.user_Language=='pt'){
this.language="Portuguese"
}else{
this.language="English"
}
if(this.user_role=='25'){
this.role='Inspector';
}else if(this.user_role=='35'){
this.role='Team Lead';
}else if(this.user_role=='45'){
this.role='Moderator';
}else if(this.user_role=='55'){
this.role='Administrator';
}else if(this.user_role=='65'){
this.role='Super Administrator';
}
}
editProfile(){
console.log(this.decideEditProfile);
console.log("edit profile function")
this.decideEditProfile=true;
}
SaveProfile(){
console.log(this.decideEditProfile);
console.log("edit profile function")
this.decideEditProfile=false;
this.useredit();
}
ionViewDidLoad() {
console.log('ionViewDidLoad ProfilePage');
}
showToast(position: string) {
let toast = this.toastCtrl.create({
message: this.editStatus.message,
duration: 2000,
position: 'top'
});
toast.present(toast);
}
useredit() {
const loader = this.loadingCtrl.create({
content: "Please wait...",
duration: 3000
});
loader.present();
let passingValue = {
"user_id": '3',
"inputName": 'James Red',
"inputEmail":'moderator#gmail.com.in',
"inputPassword":'123456'
}
this.apiConnect.postEditProfile(
JSON.stringify(passingValue)).subscribe((data) => {
console.log("login api "+JSON.stringify(data));
this.editStatus = data;
if (this.editStatus.status == "success") {
localStorage.removeItem("userName");
localStorage.removeItem("userEmail");
localStorage.removeItem("userMobile");
localStorage.removeItem("userAvatar");
localStorage.removeItem("userLanguage");
localStorage.setItem("userName",this.editStatus.Profile.fullName);
localStorage.setItem("userEmail",this.editStatus.Profile.emailAddress);
localStorage.setItem("userMobile",this.editStatus.Profile.mobile);
localStorage.setItem("userAvatar",this.editStatus.Profile.avatar);
localStorage.setItem("userLanguage",this.editStatus.Profile.languagePreference);
this.showToast('top');
this.navCtrl.push("DashBoardPage");
}
else {
this.showToast('top');
}
loader.dismiss();
})
}

From your question you are trying to say that even after updating the localstorage you are getting the old value or undefined.
So it might be possible that the data which you are returning may be null or empty. You have to carefully debug your application because localstorage do not work this same way. Do a console test.
Also in this piece of code :
if (this.editStatus.status == "success") {
localStorage.removeItem("userName");
localStorage.removeItem("userEmail");
localStorage.removeItem("userMobile");
localStorage.removeItem("userAvatar");
localStorage.removeItem("userLanguage");
localStorage.setItem("userName",this.editStatus.Profile.fullName);
localStorage.setItem("userEmail",this.editStatus.Profile.emailAddress);
localStorage.setItem("userMobile",this.editStatus.Profile.mobile);
localStorage.setItem("userAvatar",this.editStatus.Profile.avatar);
localStorage.setItem("userLanguage",this.editStatus.Profile.languagePreference);
this.showToast('top');
this.navCtrl.push("DashBoardPage");
}
You do not have to remove the items unnecessarily you can just set the localstorage and the old values will be replaced by the new values.
I hope this helps you. Thanks!

Related

Unable to skip login page after logging in once ionic 3

I am making a login app with MySQL database. I have already done login but when I close my app or press the back button of my mobile, it starts from login page again.
I tried to save the login data in local storage but it does not work. I have been searching online for some answers but I can't seem to find the solution.
Below is my code
login.ts
signIn(page) {
if(this.username.value==""){
let alert = this.alertCtrl.create({
title:"ATTENTION",
subTitle:"Username field is empty",
buttons: ['OK']
});
alert.present();
}else if(this.password.value=="") {
let alert = this.alertCtrl.create({
title:"ATTENTION",
subTitle:"Password field is empty",
buttons: ['OK']
});
alert.present();
}
else {
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json' );
let options = new RequestOptions({ headers: headers });
let data = {
username: this.username.value,
password: this.password.value
};
let loader = this.loading.create({
content: 'Processing please wait…',
});
loader.present().then(()=>{
this.http.post('http://mybusket.com/webapi/carapi/logincheck.php',data,options)
.map(res=>res.json())
.subscribe(res=>{
console.log(res)
loader.dismiss()
if(res>0) {
localStorage.setItem('response',JSON.stringify(res));
console.log(JSON.parse(localStorage.getItem('response')));
this.navCtrl.push(page)
}
else{
let alert = this.alertCtrl.create({
title:"ERROR",
subTitle:"Your Login Username or Password is invalid",
buttons: ['OK']
});
alert.present();
}
});
});
}
}
when I click the button, SignIn function runs and navigates to the menu page which is connected to welcome page.
menu.ts
export class MenuPage {
rootPage = 'Welcome';
pages = [
{ title: 'Home', component: 'Welcome' },
{ title: 'Qr Code', component: 'QrPage' },
{ title: 'Logout', component: 'LogoutPage' }
];
#ViewChild('content') nav: NavController;
constructor(public navCtrl: NavController, public navParams: NavParams)
{
}
ionViewDidLoad() {
console.log('ionViewDidLoad MenuPage');
}
openPage(page) {
// Reset the content nav to have just this page
// we wouldn't want the back button to show in this scenario
this.nav.setRoot(page.component);
}
}
I am working with lazy loading in ionic 3.
I want it so that when I log in the app, it does not require login again also when I press back button of my device app switches off.
When you login, you only save the response to your local storage. You dont have a checker if you are already logged in or not. So to stay logged in the app, you need to have a checker.
If you logged in successfully, create an item in local storage. For example, set an item isLoggedIn to true.
localStorage.setItem('isLoggedIn',true);
When you exit and re-launch the app, first thing you will do is to check the isLoggedIn from your local storage. If it is true, then navigate to the Welcome page. Otherwise, go to the Login page.
When you logout, make sure to change the isLoggedIn to false, or simply remove it.
EDIT:
Depending on your rootpage for the whole app which you can locate in your app.component.ts. (rootpage is the first page that will be shown when opening your app)
If your rootpage for the whole app is your Signin page,
your .ts file should have
constructor{
//check if the isLoggedIn in the local storage exists or is true
if(localstorage.getItem('isLoggedIn')){
// if it is true, set the menupage (which is connected to your welcome page) as root.
this.navCtrl.setRoot(MenuPage);
}
}
Additionally, in your Signin page. In your signin(page) method, adjust this
if(res>0) {
localStorage.setItem('response',JSON.stringify(res));
console.log(JSON.parse(localStorage.getItem('response')));
// add this
// set the isLoggedIn to true
localStorage.setItem('isLoggedin', true);
this.navCtrl.push(page)
}
PS> this may not work syntactically correct as I can't see your whole code. This is for your guide only, adjust the code if necessary.

If condition using storage.set is not working in Ionic

Brief Explanation of what is happening: When I open the app on mobile, it directly takes me to dashboard.html from login.html
What I am trying to achieve: When app is opened for the 1st time, after giving username and password, on success response username and password information is saved in local storage. From the next time when app is opened, app goes to login.html, in its ngOnInit() it checks if user is already logged in then it navigates to 'dashboard.htmlelse stays atlogin.html` page.
But it takes me to dashboard.html even at the very first time after app is installed. What am I doing wrong ?
login.ts code:
ngOnInit()
{
if(this.storage.get('user').then((val) => {
if(val===''){
console.log("this key does not exists");
this.storage.set('user','');
}
else {
this.navCtrl.setRoot(DashboardPage);
console.log('user::',val);
}
console.log("i am out of if");
}))
{
}
{console.log('user',val);});
}
Please check my if condition and let me know what needs to be done.
There's no need for all your storage.get code to be inside of an if statement, it's not even possible (as far as i know, maybe if you return a boolean), you just need this
ngOnInit(){
this.storage.get('user').then((val) => {
if (val === '') {
console.log("this key does not exists");
this.storage.set('user', '');
} else {
this.navCtrl.setRoot(DashboardPage);
console.log('user::', val);
}
console.log("i am out of if");
});
}
Also you'll need to set your user as '' the first time your app is opened, if you don't do this your val will be null and it'll fall to your else and your user'll gain access to DashboardPage everytime even without beeing logged or having an account at all.
So it would be better if you don't set your user as '', just don't set it and leave it to be null, then you can do as this
ngOnInit(){
this.storage.get('user').then((val) => {
if (val) {
this.navCtrl.setRoot(DashboardPage);
console.log('user::', val);
} else {
console.log("this key does not exists");
}
console.log("i am out of if");
});
}
Hope this helps.

VueJS: Redirecting between two pages

I use Firebase with VueJS (and VueRouter).
I have a problem with redirecting. I want to redirect between two pages. The first page is used for authentication and the second one for content that should only be visible to logged-in users.
My state holds the firebase user key (which will be populated through a mutation, that calls firebase):
state: {
user: { key: null }
}
The authentication page these lines:
beforeCreate() {
if (this.$store.state.user.key !== null) {
this.$router.replace('/')
}
}
And the secret page these:
beforeCreate() {
if (this.$store.state.user.key === null) {
this.$router.replace('/new')
}
}
But: the redirect from the authentication page to the secret page doesn't take place.
My Vue-dev-tools show that the user-key is set.
What could be the solution to this problem?
EDIT:
This is the mutation that calls Firebase and sets the user-key:
updateSession(state) {
auth.onAuthStateChanged((user) => {
if (user) {
state.user.key = user.uid
}
})
}
Here is the action:
UPDATE_SESSION({ commit }) {
commit('updateSession')
}
I call the action in my root component (App.vue):
beforeCreate() {
this.$store.dispatch('UPDATE_SESSION')
}
EDIT 2:
Now my routes array:
routes: [
{ path: '/', component: Secret },
{ path: '/new', component: Authentication }
]
Take a look at the Per-Route Guards section of the docs: https://router.vuejs.org/en/advanced/navigation-guards.html
You might want to try something like the below. By putting the beforeEnter guard on the route, you are telling Vue to do that first. The next argument tells VueRouter what to do next, and can redirect if needed or continue on to the original route.
beforeEnter(to, from, next) {
if (this.$store.state.user.key === null) {
next('/new')
}
}
EDIT
You may also want to try using push instead of replace
As per the conversation we had in the comments looks like you require this:
store.dispatch can handle Promise returned by the triggered action handler and it also returns Promise. See docs.
So you can setup the login action to retirn a promise like this:
a_logInUser: ({state, commit}, userInput) => {
return new Promise((resolve, reject) => {
firebase.auth().signInWithEmailAndPassword(userInput.email, userInput.paswword);
resolve();
});
}
Then in your authentication page where you tale the login input details and click the login button , set this up as the click handler of your login button
loginUser(){
this.$store.dispatch('a_logInUser', {email: this.email, password: this.password})
.then((result) => {
this.$router.replace('/');
}, (err) => {
// stay on this pageS
//handle login error
});
}
}

Ionic - one signal push notifications sent twice

I am sending push notifications with One Signal to all users from the backend that uses Laravel like this:
OneSignal::sendNotificationToAll($notification->message);
I have set it up on the frontend side like this:
angular.module('coop.services')
.service('PushService', function(
AppSettings,
$rootScope,
$q
) {
var service = {
init: function() {
if (!window.plugins || !window.plugins.OneSignal) {
return;
}
window.plugins.OneSignal
.startInit( AppSettings.oneSignalAppId)
.endInit();
},
receivePush: function(data) {
$rootScope.$broadcast('push:received', data);
},
getDeviceId: function() {
var deferred = $q.defer();
if (window.plugins) {
window.plugins.OneSignal.getIds(function(ids) {
deferred.resolve(ids.userId);
});
}
else {
deferred.reject();
}
return deferred.promise;
}
};
return service;
});
I have tested both from the backend and from the One signal dashboard and when I am sending notification I get two notifications for each I send. One with alarm icon and one without any, what I am doing wrong?
you might have enabled mozila and Chrome with wrong settings, had similar problem I couldn't disactivate the browser though, I just made a new onesignal app and solved.

Authentication with facebook in Angularfire

This is my app.js and i am looking to diplay the user id in the URL but it doesnt work.
$scope.auth = $firebaseSimpleLogin(new Firebase(FBURL));
var userID= $scope.auth.user.id;
$scope.comments = $firebase(new Firebase(FBURL+"//users"+userID+"//Cards"));
$scope.addComment = function(e) {
if (e.keyCode != 13) {
return;
}
if ($scope.auth.user === null) {
alert("You must be logged in to leave a comment");
} else {
$scope.comments.$add({
body: $scope.newComment,
name: $scope.auth.user.name, id: $scope.auth.user.id
});
$scope.newComment = "";
e.preventDefault();
}
}
}
]);
Anyone can help me in figuring it out , what i am doing wrong there?
Thank you.
And from where do you take id ? I don`t see somehow facebook login function.
[Edit] I am playing with that just now as i am new to that too. I think you are missing
$scope.auth.$login('facebook')
This is what is working for me, where from user i am grabbing id, name and so on.
//*** FB login
$scope.fbLogin=function(){
var fbaseRef=new Firebase(FBASE)
var loginObj=$firebaseSimpleLogin(fbaseRef);
console.log("Going fbLogin")
loginObj.$login('facebook').then(function(user){
console.log("FB Login ok",user)
},function(rejection){
console.log("FB Login failes",rejection)
})
}