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.
Related
I have a PWA which works fine both online and offline (but only with the initial files). However, the offline cache (let’s say a javascript file) is not being refreshed so whenever I am offline the old javascript file is used, but when online the new version is used.
On an iPad I can use Safari to go to the website and add the PWA to the home page.
If I then go offline, it works fine – all pages work etc.
But if I make a change to say a javascript file (something like adding an alert) and also change the version in my service worker, when I am online the change is reflected but when offline it remains at the older version
To clarify let’s say from the start, on going into a page it alerts “A1”
I then change the javascript to alert “A2” and change the version in the service worker.
If I run the app when online, sure enough the app says New Update Available and All Good (some alerts from the main.js file)
Then when I go into the actual page o the alert says “A2” – so all good.
Then go offline.
The alert still says “A1”
It seems that when online it uses the server latest files but when it tries to use cache the files are old and at the moment seem to be the original files.
I have read many sites on this with no success – some suggest it will sort itself in 24 hours. Some suggest setting the maxage of the service worker to 0 (but how do you do this?). Some say the files need renaming each time they change which seems very clunky.
The service worker is definitely working
main.js
$(document).ready(function () {
'use strict';
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register("/sw.js")
.then(res => {
console.log("service worker registered");
res.onupdatefound = () => {
const installingWorker = res.installing;
installingWorker.onstatechange = () => {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller){
alert("new update available");
forceReload();
}
else {
alert("all good");
}
break;
}
}
}
})
.catch(err => console.log("service worker not registered", err))
}
});
const forceReload = () =>{
console.log("ForceReload");
navigator.serviceWorker
.getRegistrations()
.then((registrations) =>{
console.log(registrations);
//alert("reg");
Promise.all(registrations.map((r) => r.unregister()))
caches.keys().then(function(names) {
for (let name of names)
caches.delete(name);
});
},
)
.then(() => {setTimeout(() => {
location.reload();
}, 500);
})
}
sw.js
let version =5; // update this to send update.
var cacheName = 'cacheV5'
var filesToCache = [
'/',
'/manifest.json',
'/index.html',
'/sales10.html',
'/getdata.html',
....
....
'/js/siteJS/sales10.js',
'/js/siteJS/getdata.js',
'/js/jquery/3.4.1/jquery.min.js',
'/js/bootstrap/bootstrap.min.js',
'/js/bootstrap/popper.min.js'
];
/* Start the service worker and cache all of the app's content */
self.addEventListener('install', function(e) {
self.skipWaiting();
e.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll(filesToCache);
})
);
});
/* Serve cached content when offline */
self.addEventListener('fetch', function(e) {
e.respondWith(
caches.match(stripQueryStringAndHashFromPath(e.request.url.replace(/^.*\/\/[^\/]+/, ''))).then(function(response) {
return response || fetch(e.request);
})
);
});
function stripQueryStringAndHashFromPath(url) { //added this so when url paramerters passed grabbing the cashed js works
return url.split("?")[0].split("#")[0];
}
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
return true;
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
});
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!
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
});
}
}
JS code
console.log('Login Success');
$ionicHistory.removeBackView();
I am trying to stop to get the login view after login. But even I was logged in, if I click on back arrow of the browser, I am getting the login page. But Once I logged in I should get home page if I click on back arrow. .removeBackView() is not working properly. Please help me.
Even $ionicHistory disableBack also not working
I was having this problem. Putting removeBackView() in the next state didn't work. So instead I added this to the previous state, right before $location.path( '/app/myFirstPage' )
$ionicHistory.nextViewOptions( {
disableBack : true
} );
I also face same type of problem so use another concept, I think its help you.
if ($state.current.name == "app.home" || $state.current.name == "login") {
$ionicPopup.confirm({
title: "Confirm",
template: "Want to exit?"
}).then(function (res) {
if (res) {
navigator.app.exitApp();
}
});
} else {
navigator.app.backHistory();
}
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)
})
}