How to define optional segment parameter in Ionic Page?

拥有回忆 提交于 2020-01-03 16:50:03

问题


How it is possible to define a optional parameter in Ionic 3 PWA?

My current @IonicPage decorator looks like:

@IonicPage({
    segment: "landing/:id"
})

But the id param must be optional. If I do not pass the id, I receive this error:

Uncaught (in promise): invalid views to insert

How to do it?
Thanks in advance!


回答1:


There is no method yet.You need to send empty string when you don’t need it.That is the workaround for this now.

 this.navCtrl.push('landing', {
      'id': ''
    })



回答2:


Since Ionic 4 with Angular: One solution is the resolution of different paths, here with two optional ids in URL:

{ path: 'landing', loadChildren: () =>
  import("./landing/landing.module").then(m => m.LandingPageModule)},
{ path: 'landing/:id1', loadChildren: () =>
  import("./landing/landing.module").then(m => m.LandingPageModule)},
{ path: 'landing/:id1/:id2', loadChildren: () =>
  import("./landing/landing.module").then(m => m.LandingPageModule)}

Allways the same target. The magic will begins in component:

import { ActivatedRoute, Router } from "@angular/router";

@Component({
  selector: "landing",
  templateUrl: "./landing.page.html",
  styleUrls: ["./landing.page.scss"]
})
export class landingPage implements OnInit {

  constructor(
    private route: ActivatedRoute,
    private router: Router
  ) {}

  ngOnInit() {
    let id1= this.route.snapshot.paramMap.get("id1");
    let id2= this.route.snapshot.paramMap.get("id2");

    // Test    
    if (id1) console.log(id1);
    if (id2) console.log(id2);
  }
}

And from page to page:

this.router.navigateByUrl('/landing');
this.router.navigateByUrl('/landing/' + '123');
this.router.navigateByUrl('/landing/' + '123/333');

The order is important and so is leaving the trailing slash on the first path.



来源:https://stackoverflow.com/questions/47478443/how-to-define-optional-segment-parameter-in-ionic-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!