Issue
In my app I want the user to see this startup/welcome page when the app launches and then click a button on it to go to login and continue using the app… and next time he opens the app the app doesn't show the startup screen and goes straight to the login or home screen... I have made a storage service that saves a state if the page has been seen and a page guard that redirects based on the state...
But now I have an issue that my app keeps skipping the startup page and goes straight to login and when I try to log in it stays on this page… the console.log show that the state is set to 'done'…
here is my code if anyone can figure out what I did wrong...
app-routing.module.ts:
const routes: Routes = [
{
path: 'login',
loadChildren: () => import('./login/login.module').then( m => m.LoginPageModule),
canLoad: [AutoLoginGuard]
},
{
path: '',
redirectTo: 'startup',
pathMatch: 'full'
},
{
path: 'startup',
loadChildren: () => import('./pages/startup/startup.module').then( m => m.StartupPageModule),
canActivate:[FirstLoadGuard]
},
{
path: 'home',
loadChildren: () => import('./home/home.module').then( m => m.HomePageModule),
canLoad: [AuthGuard],
},
];
this is the code of storage.service.ts:
export class StorageService {
constructor(private storage: Storage) {
this.initStorage();
console.log('Init storage');
}
async initStorage() {
await this.storage.create();
console.log('Storage ustvarjen');
}
async setValue(key,value) {
await this.storage.set(key, value);
return true;
}
async getValue(key) {
return await this.storage.get(key);
}
}
this is the first-load.guard.ts:
export class FirstLoadGuard implements CanActivate {
constructor(
private storageService: StorageService,
private router: Router
) {}
canActivate(route: ActivatedRouteSnapshot): Promise<boolean>
{
return new Promise(resolve => {
this.storageService.getValue('first_time').then((value) => {
if (value !== null) {
this.router.navigateByUrl('/login');
console.log('guard if value: ', value);
resolve(false);
}
else {
this.storageService.setValue('first_time', 'done');
resolve(true);
}
});
});
}
}
If I have to provide more code, feel free to comment bellow and I'll add more... I trully don't know where my mistake is :(
Solution
You can use canMatch to check on the same patch, and you don't need to do redirects
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'home',
loadChildren: () => import('./pages/startup/startup.module').then( m => m.StartupPageModule),
canMatch: [() => localStorage.getItem('first_time') === null],
},
{
path: 'home',
loadChildren: () => import('./home/home.module').then( m => m.HomePageModule),
canLoad: [AuthGuard],
},
Answered By - Chris
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.