Reputation: 97
I want to pass data between pages ionic 4 without changing url.
Code:
app-routing.module.ts
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', loadChildren: './home/home.module#HomePageModule' },
{ path: 'detail/:id', loadChildren: './detail/detail.module#DetailPageModule' },
];
home.ts
nextClicked(){
this.navCtrl.navigateForward('/detail/' + '11');
}
detail.ts
ngOnInit() {
let output= this.activatedroute.snapshot.paramMap.get('id');
console.log("data recived is ",JSON.stringify(output))
}
Output: data recived is null
Also the URL in browser is changing to http://localhost:8101/contact/11
I want my url to stay like default http://localhost:8101/ is this possible in ionic 4 ?
please help and thanks in advance!
Upvotes: 0
Views: 4842
Reputation: 35
Pass your variable like this.
constructor(private router: Router){}
sampleFunction(){
this.router.navigate(['/detail', {id: "11"}]);
}
And in the page you want to extract, import all these:
import { NavParams } from '@ionic/angular';
import { Router, ActivatedRoute, Route } from '@angular/router';
Assume you want to grab that data into a variable called v1
. Grab it using ActivatedRoute
:
this.v1 = this.activatedRoute.snapshot.paramMap.get('id');
console.log(this.v1);
And make sure to import NavParams
and add these lines into your providers in app.module.ts
file:
providers: [NavParams]
Upvotes: 0
Reputation: 354
When you route between pages your URL is meant to change. so if you don't wanna change your URL then the only way is hiding and showing the components using flags. However from ionic 4, It is advisable to use Angular routing instead of Ionic Nav controller, this article can give you the insight about it
You are using NavController API to navigate but extracting the data from angular routing ActivatedRoute API. you should navigate using the Angular Routing API as below
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
...
})
export class HomeComponent {
constructor(private router: Router){}
navigate(){
this.router.navigate(['/detail', { id: "123" }]);
}
}
and then you can extract using ActivatedRoute API as below
let id = this.route.snapshot.paramMap.get('id')
Upvotes: 3