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

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

Related

ionic 5 - routing to details page with page id issue

guys , I am creating and ionic app which has details page with page id, I am trying to configure router, its not redirecting its always on main page , my code is below please check ?
parent page route
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { RecepiesPage } from './recepies.page';
const routes: Routes = [
{
path: '',
component: RecepiesPage
},
{
path: 'recipedatail',
loadChildren: () => import('./recipedatail/recipedatail.module').then( m => m.RecipedatailPageModule)
},
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class RecepiesPageRoutingModule {}
details page routing
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { RecipedatailPage } from './recipedatail.page';
const routes: Routes = [
{
path: '',
component: RecipedatailPage
},
{
path: ':recipeId',
loadChildren: () => import('./recipedatail.module').then( m => m.RecipedatailPageModule)
},
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class RecipedatailPageRoutingModule {}
Check the angular documentation for correct router implementation

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'

PageNotFound route in root routes triggered after outsourcing routes to component

my routes used to work fine when they were all together, the notfound route
{ path: '**', component: PageNotFoundComponent}
was at the last place to capture any other not defined paths.
After I moved the recipe routes to its own module these are never called. Instead, the pagenotfound is called.
Everything works fine if I remove the PageNotFoundComponent route from the root routes. Any ideas regarding whats going on here?
This is the root app routing module:
import { Routes, RouterModule } from '#angular/router';
import { NgModule, OnInit } from '#angular/core';
import { ShoppingListComponent } from './shopping-list/shopping-list.component';
import { PageNotFoundComponent } from './errors/page-not-found/page-not-found.component';
import { AuthComponent } from './auth/auth.component';
const appRoutes: Routes = [
{ path: '', redirectTo: 'recipes', pathMatch: 'full' },
{ path: 'shopping-list', component: ShoppingListComponent },
{ path: 'auth', component: AuthComponent },
{ path: '**', component: PageNotFoundComponent}
];
#NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule {
OnInit() {
console.log(appRoutes);
}
}
This is the child recipe routing module:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { RecipesComponent } from './recipes.component';
import { AuthGuard } from '../auth/auth.guard';
import { RecipeStartComponent } from './recipe-start/recipe-start.component';
import { RecipeEditComponent } from './recipe-edit/recipe-edit.component';
import { RecipeDetailComponent } from './recipe-detail/recipe-detail.component';
import { RecipesResolverService } from './recipes-resolver.service';
const routes: Routes = [
{
path: 'recipes', component: RecipesComponent, canActivate: [AuthGuard] , children: [
{ path: '', component: RecipeStartComponent },
{ path: 'new', component: RecipeEditComponent },
{
path: ':id',
component: RecipeDetailComponent,
resolve: [RecipesResolverService]
},
{
path: ':id/edit',
component: RecipeEditComponent,
resolve: [RecipesResolverService]
},
]
}
];
#NgModule({
declarations: [
],
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class RecipesRoutingModule {
}
Thanks for taking the time to get this far, any idea would be appreciated.
The problem was that the wildcard route ('**') always should be at the end of your routes list because of the way it works.
It watches all the routes before it, and checks if any given URL, that the user is searching on matches those.
Since you've outsourced your recipes paths, and probably imported them into app.module, those paths get concatenated after the original path list that you have in your app-routing.module.
Therefore your paths in the recipe routing module end up being AFTER the wildcard route ('**'), so they get ignored by it. That's why searching on any URL listed in the recipe routing module will reroute the user to the wild card path, to your PageNotFoundComponent.
Great solution tho.
I solved the problem lazy loading all the routes and then adding the PageNotFound route '**' at the end, hope this helps anyone that faced the same problem:
import { Routes, RouterModule } from '#angular/router';
import { NgModule } from '#angular/core';
import { PageNotFoundComponent } from './errors/page-not-found/page-not-found.component';
// If new and :id children were inverted that would make angular take new as id
// ant that would break the app, the order of the routes is very important
// that's why the 404 PageNotFoundComponent goes the last one
const appRoutes: Routes = [
{ path: '', redirectTo: 'recipes', pathMatch: 'full' },
{ path: 'recipes', loadChildren: () => import('./recipes/recipes.module').then(m => m.RecipesModule) },
{ path: 'shopping-list', loadChildren: () => import('./shopping-list/shopping-list.module').then( m => m.ShoppingListModule) },
{ path: 'auth', loadChildren: () => import('./auth/auth.module').then( m => m.AuthModule) },
{ path: '**', component: PageNotFoundComponent }
];
#NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}

Navigate from Login page to Tabs in Ionic4?

I am creating an application and i want move from login Page to Tabs Page. When I try to navigate to Tabs page, its only showing Home page without Tabs.
here is my Code.
app-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', loadChildren: './pages/login/login.module#LoginPageModule' },
{ path: 'tabs', loadChildren: './pages/tabs/tabs.module#TabsPageModule' }
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
tabs.module.ts
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 { TabsPageRoutingModule } from './tabs.router.module';
import { TabsPage } from './tabs.page';
import { HomePageModule } from '../home/home.module';
import { ActivityPageModule } from '../activity/activity.module';
import { MygroupsPageModule } from '../mygroups/mygroups.module';
import { MessagesPageModule } from '../messages/messages.module';
import { SettingsPageModule } from '../settings/settings.module';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
TabsPageRoutingModule,
HomePageModule,
ActivityPageModule,
MygroupsPageModule,
MessagesPageModule,
SettingsPageModule
],
declarations: [TabsPage]
})
export class TabsPageModule {}
tabs.router.module.ts
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { TabsPage } from './tabs.page';
import { HomePage } from '../home/home.page';
import { ActivityPage } from '../activity/activity.page';
import { MygroupsPage } from '../mygroups/mygroups.page';
import { MessagesPage } from '../messages/messages.page';
import { SettingsPage } from '../settings/settings.page';
const routes: Routes = [
{
path: 'tabs',
component: TabsPage,
children: [
{
path: '',
redirectTo: '/tabs/(home:home)',
pathMatch: 'full',
},
{
path: 'home',
outlet: 'home',
component: HomePage
},
{
path: 'activity',
outlet: 'activity',
component: ActivityPage
},
{
path: 'mygroups',
outlet: 'mygroups',
component: MygroupsPage
},
{
path: 'messages',
outlet: 'messages',
component: MessagesPage
},
{
path: 'settings',
outlet: 'settings',
component: SettingsPage
}
]
}
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class TabsPageRoutingModule {}
From Login page, I am navigating in this way.
this.router.navigate(['tabs']);
but this is just showing a home page with no tabs. Can you guide me what should i do, even tabs are not showing in DOM, i tried to inspect them.
It is just showing Home Page as default Page.
I had the same issue, the navigation doen't work in tabs' page. To avoid the issue I did this :
this.navCtrl.navigateRoot('/home'); // I use NavCtroller instead of Router
and in app-routing.module.ts :
{ path: 'home', redirectTo: '/tabs/(home:home)' },
I hope it will work properly in the next beta.

IONIC 2 Cloud Push Not Working - App Crashes

I have created IONIC 2 App and at the final stage I am trying to implement the IONI Cloud Push but it is not working and every time App crashing whenever I enable the cloud push register function:
this.push.register().then((t: PushToken) => {
return this.push.saveToken(t);
}).then((t: PushToken) => {
console.log('Token saved:', t.token);
});
I am running the build using 'ionic run android' in my real device
Please help me what i am doing wrong. have checked many articles everywhere it says same process what I have already implemented:-
npm install #ionic/cloud-angular --save
cordova plugin add phonegap-plugin-push --variable SENDER_ID=12341234 --save
ionic io init
and all other configurations.
Below is my app.component.ts
import { Component, ViewChild } from '#angular/core';
import { Nav, Platform, ToastController } from 'ionic-angular';
import { Events } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { Storage } from '#ionic/storage';
import { TabsComponent } from '../pages/tabs/tabs-component/tabs.component';
import { LoginComponent } from '../pages/login/login-component/login.component';
import { Push, PushToken } from '#ionic/cloud-angular';
//import { Push } from 'ionic-native';
//import { CloudSettings, CloudModule } from '#ionic/cloud-angular';
//import { Push, PushObject, PushOptions } from "#ionic-native";
#Component({
templateUrl: './app.html',
})
export class BanglaliveApp {
#ViewChild(Nav) nav: Nav;
rootPage = TabsComponent;
user: any;
pages: Array<{title: string, component: any, category: any}>;
constructor(
public push: Push,
public platform: Platform,
private storage: Storage,
private toastController: ToastController,
public events: Events
) {
this.initializeApp();
events.subscribe('userloggedin', user => {
if(user){
this.user = user;
}
});
storage.get('wordpress.user').then((value) => {
if (value) {
this.user = value;
}
});
this.pages = [
{ title: '????? ????', component: TabsComponent, category: { class:'home' }},
{ title: '?????????', component: LoginComponent, category: {class: 'category'}}
];
}
initializeApp() {
this.platform.ready().then(() => {
// Enable RTL Support
// this.platform.setDir('rtl', true);
StatusBar.styleDefault();
Splashscreen.hide();
// ############## P U S H ###############
this.push.register().then((t: PushToken) => {
return this.push.saveToken(t);
}).then((t: PushToken) => {
console.log('Token saved:', t.token);
});
// this.push.rx.notification()
// .subscribe((msg) => {
// alert(msg.title + ': ' + msg.text);
// });
// ############## P U S H ###############
});
}
openPage(page, index) {
//check if page or post has been called
this.nav.setRoot(page.component);
}
}
login(){
this.nav.push(LoginComponent);
}
logout() {
this.user = undefined;
this.storage.remove('wordpress.user');
this.nav.setRoot(LoginComponent);
}
profile() {
this.nav.push(ProfilePage);
}
}
and here is my app.module.ts:-
import { NgModule, ErrorHandler } from '#angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { SharedModule } from './shared/shared.module'
import { TabsModule } from '../pages/tabs/tabs.module';
import { SignUpModule } from '../pages/signup/signup.module'; //SSSS
import { ProfileModule } from '../pages/profile/profile.module'; //SSSS
import { MyApp} from './app.component';
import { CloudSettings, CloudModule } from '#ionic/cloud-angular';
const cloudSettings: CloudSettings = {
'core': {
'app_id': 'XXXXXX',
},
'push': {
'sender_id': 'XXXXXXXX',
'pluginConfig': {
'ios': {
'badge': true,
'sound': true
},
'android': {
'iconColor': '#343434'
}
}
}
};
#NgModule({
declarations: [
MyApp
],
imports: [
IonicModule.forRoot(MyApp, {
backButtonIcon: 'arrow-back'
}),
CloudModule.forRoot(cloudSettings),
SharedModule,
TabsModule,
SignUpModule,
ProfileModule,
],
bootstrap: [IonicApp],
entryComponents: [
MyApp
],
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}]
})
export class AppModule {}
Please help..!!
Thanks
It's working perfectly fine for me on real device.
Play with Git Repo.
app.component.ts
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { Push, PushToken } from '#ionic/cloud-angular';
import { HomePage } from '../pages/home/home';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage: any = HomePage;
constructor(platform: Platform, public push: Push) {
platform.ready().then(() => {
this.push.register().then((t: PushToken) => {
return this.push.saveToken(t);
}).then((t: PushToken) => {
console.log('Token saved:', t.token);
});
this.push.rx.notification()
.subscribe((msg) => {
alert(msg.title + ': ' + msg.text);
});
});
}
}
app.module.ts
import { CloudSettings, CloudModule } from '#ionic/cloud-angular';
const cloudSettings: CloudSettings = {
'core': {
'app_id': '525f53a4'
},
'push': {
'sender_id': '837506444622',
'pluginConfig': {
'ios': {
'badge': true,
'sound': true
},
'android': {
'iconColor': '#343434'
}
}
}
};
#NgModule({
declarations: [
],
imports: [
CloudModule.forRoot(cloudSettings)
],
bootstrap: [IonicApp],
entryComponents: [
],
providers: [
]
})
export class AppModule { }
Finally I found the outdated cordova splash plugin was causing this error and reinstall was not upgrading because in config.xml had the old version of the plugin.
I just deleted the plugin and removed lines from config.xml and reinstalled and it worked.
Just in case it may work for someone else also.