[Fixed] I want to pass data between pages ionic 4

Issue

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!

Solution

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')

Leave a Reply

(*) Required, Your email will not be published