How to create authenticate in certain tabs - ionic-framework

I just created a new ionic project with Starter template tabs, then i want to authenticate only in tab 3, but when I declare canActivate: [AuthGuardService] on routes tabs, I can’t access tabs 3 if auth value is false. because other tabs can be accessed without requiring authentication.
this is my code
tabs-routing.module.ts
AuthGuardService] on routes tabs, I can’t access tabs 3 if auth value is false. because other tabs can be accessed without requiring authentication.
this is my code
tabs-routing.module.ts
const routes: Routes = [
{
path: 'tabs',
component: TabsPage,
children: [
{
path: 'tab1',
children: [
{
path: '',
loadChildren: () =>
import('../tab1/tab1.module').then(m => m.Tab1PageModule)
}
]
},
{
path: 'tab2',
children: [
{
path: '',
loadChildren: () =>
import('../tab2/tab2.module').then(m => m.Tab2PageModule)
}
]
},
{
path: 'tab3',
canActivate: [AuthGuardService], /* <-- check auth */
children: [
{
path: '',
loadChildren: () =>
import('../tab3/tab3.module').then(m => m.Tab3PageModule)
}
]
},
{
path: 'tab4',
children: [
{
path: '',
loadChildren: () =>
import('../tab4/tab4.module').then(m => m.Tab4PageModule)
}
]
},
{
path: '',
redirectTo: '/tabs/tab1',
pathMatch: 'full'
}
]
},
{
path: '',
redirectTo: '/tabs/tab1',
pathMatch: 'full'
}
];
auth-guard.service.ts
export class AuthGuardService implements CanActivate{
constructor(
private authService: AuthenticationService,
) { }
canActivate(): boolean{
return this.authService.isAuthenticated();
}
}

Related

Setting opening page in app-routing module doesn't redirect as expected

I have walkthrough page built using ion-slides.
I had set this page to be the first page to open when the app had launched in app-routing.module.ts:
{
path: '',
redirectTo: 'walkthrough',
pathMatch: 'full'
},
However if I change the starting page to any other page the app will consistently start with the waklthourgh page:
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
All paths are set correctly:
{
path: 'walkthrough',
loadChildren: () => import('./walkthrough/walkthrough.module').then(m => m.WalkthroughPageModule)
},
{
path: 'login',
loadChildren: () => import('./auth/login/login.module').then( m => m.LoginPageModule)
},
Any input appreciated.
EDIT: adding login routing.module.ts:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { LoginPage } from './login.page';
const routes: Routes = [
{
path: '',
component: LoginPage
}
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class LoginPageRoutingModule {}

Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'tabs/tab1'

I created a ionic tabs app, and I needed to change home page.
I did it changing the app-routing.module.ts file with this:
const routes: Routes = [
{
path: '',
redirectTo: '/start-page', pathMatch: 'full'
//loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
},
{
path: 'home',
loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
},
{
path: 'start-page',
loadChildren: () => import('./start-page/start-page.module').then( m => m.StartPagePageModule)
}
];
It works. start-page is called for first.
In start-page page, I just wanna redirect to tabs page. So I did something like this in start-page.page.ts file:
ngOnInit() {
this.router.navigate(['home']);
}
But I get this error:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes.
URL Segment: 'tabs/tab1'
P.S. I did not change tabs page at all. It's the one ionic created for me starting the project.
If I decomment the line loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule) (and delete the redirect one) the app starts with tabs page without errors.
Can you try placing Empty selector at the bottom
const routes: Routes = [
{
path: 'home',
loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
},
{
path: 'start-page',
loadChildren: () => import('./start-page/start-page.module').then( m => m.StartPagePageModule)
},
{
path: '',
redirectTo: '/start-page', pathMatch: 'full'
//loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
}
];
As it is a tabs app the below code must be present in app.routing.ts
{
path: 'tabs',
loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
}
This problem occurs when the following lines do not exist in the module file:
imports: [
RouterModule.forChild(routes)
],
exports: [RouterModule]

How to trigger ionViewWillLeave in Ionic 4 with route in tabs.router.module

Lifecycle hooks ionViewWillLeave / ionViewDidLeave are not triggered when placing all pages routes in TabsPageRoutingModule.
We changed the routes from app-routing.module.ts to tabs.router.module.ts to get full view of the tabbar in the Ionic 4 app. The routes works perfectly.
When the routes were in app-routing.module.ts, the ionViewWillLeave was always triggered when leaving the page (and closing the present Observables). Now the ionViewWillLeave is not triggered when leaving the page.
Route in tabs.router.module.ts
const routes: Routes = [
{
path: 'tabs',
component: TabsPage,
children: [
{
path: '',
redirectTo: '/tabs/(home:home)',
pathMatch: 'full',
},
{
path: 'home',
outlet: 'home',
component: HomePage
},
{
path: 'chats',
outlet: 'chats',
component: ChatsPage
},
...
Logging failed for ionViewWillLeave in TS file
ionViewWillEnter() {
console.log('ionViewWillEnter'); // <- In console when entering
}
ionViewWillLeave() {
console.log('ionViewWillLeave'); // <- Not in console when leaving
}
Can't figure out why the ionViewWillLeave is not printed anymore. Any help is appreciated.
Route in app-routing.module.ts
const routes: Routes = [
{ path: '', loadChildren: './tabs/tabs.module#TabsPageModule' },
{ path: 'chats', loadChildren: './chats.module#ChatsPageModule' },
...
Logging success for ionViewWillLeave in TS file
ionViewWillEnter() {
console.log('ionViewWillEnter'); // <- In console when entering
}
ionViewWillLeave() {
console.log('ionViewWillLeave'); // <- In console when leaving
}
Solution for our problem
Breaking changes to tabs
4.0.0-beta.18 (2018-12-13)
Stopped using outlet/component in tab-router, now we directly place children pages in the tabbed path.
{
path: 'tabs',
component: TabsPage,
children: [
{
path: 'home',
children: [
{
path: '',
loadChildren: '../home/home.module#HomePageModule'
},
{
path: 'chats'
children: [
{
path: '',
loadChildren: '../chats/chats.module#ChatsPageModule'
}
]
},
...

Named router and nested routes in angular 6

Can someone please assist in navigating to a specific route. I've been sitting with this for hours now. Here's what I have:
const routes: Routes = [
{
path: '', redirectTo: 'home', pathMatch: 'full'
},
{
path: 'home',
component: MainlayoutComponent,
canActivate: [AuthenticatedGuard],
children: [
{ path: 'listmanagement', component: ListmanagementComponent, outlet: 'main' },
{
path: 'buildings', component: BuildingslistComponent, outlet: 'main',
children: [
{ path: '', redirectTo: 'buildings', pathMatch: 'full' },
{ path: 'building', component: BuildingdetailComponent },
{ path: 'building/:code', component: BuildingdetailComponent }
]
},
{
path: 'calendarandrates', component: CalendarandratesComponent, outlet: 'main',
children: [
{ path: '', redirectTo: 'calendarandrates', pathMatch: 'full' },
{ path: 'rescalendar', component: RescalendarlistComponent },
{ path: 'roomrates', component: ResratesmainComponent },
]
},
{ path: 'users', component: UsersComponent, outlet: 'main' },
]
},
{
path: 'login',
component: LoginlayoutComponent,
children: [
{ path: '', component: LoginComponent, outlet: 'login' },
]
},
{
path: '**',
component: NotfoundComponent,
canActivate: [AuthenticatedGuard],
outlet: 'main'
}
];
Then in my app.component I only have the primary router outlet:
<router-outlet></router-outlet>
This router outlet is suppose to load only one of the two layout components, maned loginlayout.component and mainlayout.component: One for when a user is not logged in (so as not to show the side nav and other toolbar items, this layout component only has a simple logo on the top left and header in the middle), and other layout component has side nav and more items on the toolbar. All this is working fine and I'm able to log in using the first layout and load the 2nd layout. The outlet routers in the respective layout pages are:
<router-outlet name="login"></router-outlet>
<router-outlet name="main"></router-outlet>
Somehow, once in the main layout component, I can navigate to the 1st level child (buildings, for example) using something like:
this.router.navigate(['/home', { outlets: { main: ['buildings'] } }])
I cannot seem to figure out how I can navigate to the 2nd later child (for example, once in the buildings component, I want to navigate to the (single) building item by clicking an edit (with param) or add (without param) new button
I've search and I only get examples with only one level child, but not 2 levels as I have in this example. Any help would be appreciated.
I fixed my issue and just carried on with the development. Now that I'm done, I thought I should just post my fix. I changed the routes to look like this:
const routes: Routes = [
/*==================================Main Outlet==================================*/
{
path: '', redirectTo: 'home', pathMatch: 'full'
},
{
path: 'home', component: MainlayoutComponent, canActivate: [AuthGuard],
children: [
{ path: '', component: HomeComponent, outlet: 'main' },
{ path: 'listmanagement', component: ListmanagementComponent, outlet: 'main' },
{ path: 'buildings', component: BuildingslistComponent, outlet: 'main' },
{ path: 'buildings/building/:code', component: BuildingdetailComponent, outlet: 'main' },
{ path: 'buildings/building', component: BuildingdetailComponent, outlet: 'main' },
{ path: 'buildings/allbedspaces', component: BedspacelistComponent, outlet: 'main' },
{ path: 'calendarandrates', component: CalendarandratesComponent, outlet: 'main' },
{ path: 'calendarandrates/rescalendar', component: RescalendarlistComponent, outlet: 'main' },
{ path: 'calendarandrates/roomrates', component: ResratesmainComponent, outlet: 'main' },
{ path: 'users', component: UsersComponent, outlet: 'main' },
{ path: 'users/myaccount', component: MyaccountComponent, outlet: 'main' },
{ path: '**', component: NotfoundComponent, canActivate: [AuthGuard], outlet: 'main' }
]
},
/*==================================Login Outlet==================================*/
{
path: 'login', component: LoginlayoutComponent,
children: [{ path: '', component: LoginComponent, outlet: 'login' } ]
}
];
Then when navigating to a route I just use the following code:
this.router.navigate(['/home', { outlets: { main: ['buildings', 'allbedspaces'] } }], { skipLocationChange: true })
skipLocationChange: true because I skip all my location changes when routing and always keep the base url since I do not want users to navigate through the app using the address bar

angular2 route not working

i use angular2 rc3 and angular2/router 3.0.0-alpha.8 to do my router:
here is my code:
bootstrap(AppComponent, [HTTP_PROVIDERS, APP_ROUTER_PROVIDERS, AUTH_PROVIDERS,
{
provide: AuthHttp,
useFactory: (http:Http) => new AuthHttp(new AuthConfig({tokenName: 'jwt'}), http),
deps: [Http]
},
{
provide: TranslateLoader,
useFactory: (http:Http) => new TranslateStaticLoader(http, 'app/i18n', '.json'),
deps: [Http]
},
{provide: LocationStrategy, useClass: PathLocationStrategy},
// use TranslateService here, and not TRANSLATE_PROVIDERS (which will define a default TranslateStaticLoader)
TranslateService,
ApiService,
CookieService,
AuthenticationService
]).catch(err => console.error(err));
my router is:
export const routes:RouterConfig = [
...AccountRouters,
...DealOverviewRouters
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
export const AccountRouters: RouterConfig = [
{
path: 'account', component: AccountComponent
},
{
path: 'login', component: LoginComponent
},
];
export const DealOverviewRouters:RouterConfig = [
{
path: '',
redirectTo: '/deal-overview',
terminal: true
},
{
path: 'deal-overview', component: DealOverviewComponent
}
];
then in my app.component.ts:
constructor(public translate:TranslateService, private _service: AuthenticationService, private _router: Router) {
this.isLogin = _service.isLogin;
console.log(_service.isLogin);
}
ngOnInit() {
// this._service.checkCredentials();
if(!this.isLogin) {
console.log(1111);
this._router.navigateByUrl('/login');
}
}
it's really print 1111 on my console log;
but the redirect to /login not working.
I can visit my localhost:3000/login page directly and nothing error.
but only this._router.navigateByUrl('/login') not working.
I've had issues with the following syntax with the new router:
export const routes:RouterConfig = [
...AccountRouters,
...DealOverviewRouters
];
instead, manually place them all into the one const and try that:
export const routes:RouterConfig = [
{
path: '',
redirectTo: '/deal-overview',
terminal: true
},
{
path: 'deal-overview', component: DealOverviewComponent
},
{
path: 'account', component: AccountComponent
},
{
path: 'login', component: LoginComponent
}
];