angular2 route not working - redirect

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
}
];

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 {}

How to create authenticate in certain tabs

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();
}
}

IONIC ERROR Error: Uncaught (in promise): Error: Cannot find module '../home/home.module' Error: Cannot find module '../home/home.module'

Firstly, when i login the error show:
ERROR Error: Uncaught (in promise): Error: Cannot find module '../home/home.module'
Error: Cannot find module '../home/home.module'
Here the code for the error part:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import {Routes, RouterModule} from '#angular/router';
import { IonicModule } from '#ionic/angular';
import { MenuPage } from './menu.page';
const routes: Routes =[
{
path: '',
component: MenuPage,
children: [
{
path: 'home',
loadChildren: '**../home/home.module#HomePageModule**'
}, /* '../home/home.module#HomePageModule' */
{
path: 'tabs',
loadChildren: () => import('../tabs/tabs.module').then( m => m.TabsPageModule)
}, /* '../tabs/tabs.module#TabsPageModule' */
{
path: 'status',
loadChildren: '../status/status.module#StatusPageModule'
},
{
path: 'butiranmaklumat',
loadChildren: '../butiran-maklumat/butiran-maklumat.module#ButiranMaklumatPageModule'
},
{
path: 'tabs/butiranmaklumat',
loadChildren: '../butiran-maklumat/butiran-maklumat.module#ButiranMaklumatPageModule'
},
{
path: 'butiranpekerjaan',
loadChildren: '../butiran-pekerjaan/butiran-pekerjaan.module#ButiranPekerjaanPageModule'
},
{
path: 'tabs/butiranpekerjaan',
loadChildren: '../butiran-pekerjaan/butiran-pekerjaan.module#ButiranPekerjaanPageModule'
},
{
path: 'butiranpasangan',
loadChildren: '../butiran-pasangan/butiran-pasangan.module#ButiranPasanganPageModule'
},
{
path: 'tabs/butiranpasangan',
loadChildren: '../butiran-pasangan/butiran-pasangan.module#ButiranPasanganPageModule'
},
{
path: 'maklumattanggungan',
loadChildren: '../maklumat-tanggungan/maklumat-tanggungan.module#MaklumatTanggunganPageModule'
},
{
path: 'tabs/maklumattanggungan',
loadChildren: '../maklumat-tanggungan/maklumat-tanggungan.module#MaklumatTanggunganPageModule'
},
{
path: 'sejarahpermohonan',
loadChildren: '../sejarah-permohonan/sejarah-permohonan.module#SejarahPermohonanPageModule'
},
{
path: 'tabs/sejarahpermohonan',
loadChildren: '../sejarah-permohonan/sejarah-permohonan.module#SejarahPermohonanPageModule'
}
/* {
path: '',
redirectTo: 'home',
pathMatch: 'full'
}
*/
]
}
];
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
RouterModule.forChild(routes)
],
declarations: [MenuPage]
})
export class MenuPageModule {}
So, i try to delete ".." on the bold line and write back ".." . and it can successfully login.
But the other error show:
ERROR TypeError: datas.pr_master_pengguna is not iterable
Here the code for this part:
import { Component, OnInit } from '#angular/core';
import {Provider} from '../../providers/provider';
import {Router} from '#angular/router';
import {Storage} from '#ionic/storage';
#Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage {
LoginPengguna:string;
KataLaluan:string;
task:any[];
constructor(
private provider:Provider,
private router:Router,
private storage: Storage
) { }
login(){
return new Promise(resolve =>{
let body = {
LoginPengguna:this.LoginPengguna,
KataLaluan:this.KataLaluan
};
this.provider.postData(body, 'login.php').subscribe(data => {
// console.log(data);
if(data['user']){
this.storage.set('IdPengguna', data['user'][0]['IdPengguna']);
this.router.navigate(['menu/tabs/tabs/home']);
}else {
alert("Login failed");
}
});
})
}
}
but for this error, i just refresh it and data show.
So i try to terminate and run it back. and the error still show the same. it just like cache in my code.
Hopefully u guys can help.
Error was this part
children: [
{
path: 'home',
loadChildren: '**../home/home.module#HomePageModule**'
}, /* '../home/home.module#HomePageModule' */
change it
// Full path including `src` at the start:
loadChildren: '/home/home.module#HomePageModule'
or this:
// Relative path from the `app-routing.module.ts` file:
loadChildren: './home/home.module#HomePageModule'

How to do a lazy loaded ionic framework app with a login page

I have an app that is working great, but I want to move it behind a login page. The various modules are lazy-loaded and have been working great. However, when I change the app to always go to the login page first (where I will check login status and redirect to the app if logged in), I get an error about routes.
app-routing.module.ts
import { NgModule } from '#angular/core';
import { PreloadAllModules, RouterModule, Routes } from '#angular/router';
const routes: Routes = [
{ path: '', loadChildren: './login/login.module#LoginPageModule' }
// this next line was how the app routed before I tried adding the login page
// { path: '', loadChildren: './tabs/tabs.module#TabsPageModule' }
];
#NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule {}
login.router.module.ts
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { LoginPage } from './login.page';
const routes: Routes = [
{ path: '', component: LoginPage },
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class LoginRoutingModule { }
login.page.ts
import { ChangeDetectionStrategy, Component } from '#angular/core';
import { Router } from '#angular/router';
import { Store } from '#ngrx/store';
import { AppState } from '../_store/store/app.store';
import { filter } from 'rxjs/operators';
#Component({
selector: 'app-login',
templateUrl: 'login.page.html',
styleUrls: ['login.page.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class LoginPage {
constructor(private router: Router, private store: Store<AppState>) {
this.userSubscription = this.store.select(state => state.users.user).pipe(
filter(user => !!user)
).subscribe(user => {
if (user) {
// THIS IS WHERE THE ERROR HAPPENS
this.router.navigate(['/tabs']);
}
});
}
}
this.router.navigate(['/tabs']); is where the error happens:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes.
URL Segment: 'tabs/behaviors' Error: Cannot match any routes. URL
Segment: 'tabs/behaviors'
I'm sure I'm missing something really obvious here. First attempt at lazy loading all the modules. I'm pretty certain I need to reference the tabs module in the login.page file somehow, or in the login.router.module. Any help would be greatly appreciated. The state check for user status works great, I've verified that all of that is working, it is just where it attempts to navigate if user is found.
Try to change to
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', loadChildren: './login/login.module#LoginPageModule' }
{ path: 'tabs', loadChildren: './tabs/tabs.module#TabsPageModule' }
];
With this code this.router.navigate(['/tabs']); you are routing to tabs, but you don't have it declare it. This is for the app.routing.ts file. Don't understand why you have the login.router.ts file.
So after following a suggestion above, and that giving me the same error, and finding no help in the docs for either angular or ionic, I went on a multi-hour change every combination of routings I could and finally something worked.
These are the routes in the app-routing.module.ts
{ path: 'login', loadChildren: './login/login.module#LoginPageModule' },
{ path: 'tabs', loadChildren: './tabs/tabs.module#TabsPageModule' },
{ path: '', redirectTo: 'login', pathMatch: 'full' },
This is the tabs.router.module.ts before the change that made it work:
{ path: 'tabs', component: TabsPage, children: [ .... ] },
{ path: '', redirectTo: 'tabs/behaviors', pathMatch: 'full' }
This is it now:
{ path: '', component: TabsPage, children: [ ... ] },
That's it. Finally figured it out when accidentally typing in the browser .com:8100/tabs/tabs/behaviors worked. Removing the path: 'tabs' in the tabs routing module fixed it. /tabs goes to the tabs routing, and then /behaviors is the child. My code had added a 2nd layer of /tabs in between the 1st and the /behavior.

LazyLoading routing each time creates new Component in memory and does not destroy it after loading new same component

I use:
nativescript 4.2
angular 6.0.0
page-router-outlet
navigation from page to page by 'lazyloading' (lateral navigation):
export const routes = [
{
path: "",
loadChildren: "~/pages/start-page/start-page.module#StartPageModule"
},
{
path: "login",
loadChildren: "~/pages/login/login.module#LoginModule"
}, ...
navigate with RouterExtensions with 'clearHistory = true'
When i navigate from page 'Home' to another page and return to 'Home' i see in memory two component 'HomeComponent'. When I repeat the operation their becomes three, four, five, .....
chrome debug window
Try to this for lazy loading routing.
app-routing.module.ts :-
import { NgModule } from "#angular/core";
import { Routes } from "#angular/router";
import { NativeScriptRouterModule } from "nativescript-angular/router";
const routes: Routes = [
{ path: "", redirectTo: "/login", pathMatch: "full" },
{ path: "startpage", loadChildren: "~/pages/start-page/start-page.module#StartPageModule" },
{ path: "login", loadChildren: "~/pages/login/login.module#LoginModule" }
]
#NgModule({
imports: [NativeScriptRouterModule.forRoot(routes)],
exports: [NativeScriptRouterModule]
})
export class AppRoutingModule { }
Redirection Code:-
import { NgZone } from "#angular/core";
import { isIOS } from "tns-core-modules/platform";
import { RouterExtensions } from "nativescript-angular/router";
constructor(private zone: NgZone,
private _routerExtensions: RouterExtensions){ }
gotoStartPage() {
setTimeout(() => {
this.zone.run(() => {
this._routerExtensions.navigate(["startpage"], {
clearHistory: (isIOS) ? true : false,
});
});
}, 500);
}