【问题标题】:I want to pass data between pages ionic 4我想在 ionic 4 页面之间传递数据
【发布时间】:2021-04-06 21:26:12
【问题描述】:

我想在 ionic 4 页面之间传递数据而不更改 url。

代码:

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

输出:接收到的数据为空

浏览器中的网址也更改为http://localhost:8101/contact/11

我希望我的网址保持默认 http://localhost:8101/ 在 ionic 4 中是否可行?

请提前帮助和感谢!

【问题讨论】:

标签: angular routing angular7 ionic4


【解决方案1】:

当您在页面之间进行路由时,您的 URL 会发生变化。因此,如果您不想更改 URL,那么唯一的方法是使用标志隐藏和显示组件。但是从 ionic 4 开始,建议使用 Angular 路由而不是 Ionic Nav 控制器,这个article 可以让您了解它

您正在使用 NavController API 进行导航,但从角度路由 ActivatedRoute API 中提取数据。您应该使用 Angular Routing API 进行导航,如下所示

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

然后您可以使用以下 ActivatedRoute API 进行提取

let id = this.route.snapshot.paramMap.get('id')

【讨论】:

  • 我从哪里传递我的 'id' 参数。
  • 更新了答案以反映您的评论 this.router.navigate(['/detail', { id: "123" }]);
【解决方案2】:

像这样传递你的变量。

constructor(private router: Router){}

sampleFunction(){
   this.router.navigate(['/detail', {id: "11"}]);
}

并在你要提取的页面中,导入所有这些:

import { NavParams } from '@ionic/angular';
import { Router, ActivatedRoute, Route } from '@angular/router';

假设您想将该数据抓取到名为v1 的变量中。使用ActivatedRoute抓住它:

this.v1 = this.activatedRoute.snapshot.paramMap.get('id');
console.log(this.v1);

并确保导入NavParams 并将这些行添加到app.module.ts 文件中的提供程序中:

providers: [NavParams]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-19
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多