Ionic 4 - 如何使用 navCtrl 或 Router 服务在页面之间传递数据 [英] Ionic 4 - how to pass data between pages using navCtrl or Router service

查看:28
本文介绍了Ionic 4 - 如何使用 navCtrl 或 Router 服务在页面之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ionic 3 中,您可以使用 navController 的第二个参数将数据传递到下一页并使用 navParams 服务检索它.

In Ionic 3 you could use the second argument of the navController to pass data to the next page and retrieve it with the navParams service.

这是一个非常方便的功能.Ionic 4 中是否有用于路由的等效 api?

This was a really convenient feature. Is there an equivalent api for routing in Ionic 4?

您始终可以将对象/数组 JSON.stringify 到 routerParams,在我看来这不太方便.

You can always JSON.stringify the object/array to the routerParams, which in my opinion is less convenient.

在 Ionic 4 中,您可以使用 ComponentProps 和 @Input() 与 modalController 传递数据,使其更适合快速推送/弹出实现.

In Ionic 4 you can pass data with the modalController using ComponentProps and @Input() making it more suitable of a quick push/pop implementation.

编辑

我提出这个问题的目的是找出是否有来自 Angular 6+ 或 Ionic 4+ 的原生 API.我很清楚实现自定义服务或解析器以实现此目的的方法.

My intention with this question is to find out if there are any native APIs from Angular 6+ or Ionic 4+. I am well aware of ways to implement a custom service or resolver to accomplish this.

目标是最大限度地使用 ionic 和 angular 的 api,因为在较大的项目中,每个自定义代码都需要文档并增加了复杂性.

The goal is to use ionic's and angular's api to its fullest, since in larger projects each custom code requires documentation and increases complexity.

推荐答案

在 Ionic v4/Angular 7.2+ 中有多种方法可以将参数从一个页面传递到另一个页面:

There is multiple ways to pass a parameters from a page to another in Ionic v4 / Angular 7.2+:

1.使用 Extras 状态(自 Angular 7.2 起新增) - 推荐

简单干净

// original page
let navigationExtras: NavigationExtras = { state: { foo: this.foo } };
this.router.navigate(['destination-path'], navigationExtras);
// destination page
constructor(private route: ActivatedRoute, private router: Router) {
    this.route.queryParams.subscribe(params => {
      if (this.router.getCurrentNavigation().extras.state) {
        this.foo= this.router.getCurrentNavigation().extras.state.foo;
      }
    });
  }

2.使用服务和解析器

不完善数据但有点重.

将数据存储到服务中并使用路由器传递解析器

Store the data into a service and pass a resolver using the router

3.使用对象的 id(不推荐)

如果您的对象已存储,您可以在 url 中传递 id 并再次获取它.

If your object is stored, you can pass the id in the url and fetch it again.

它会减慢应用程序的速度,暗示该对象存储在某处并可能增加网络问题(如果未在本地存储)

It will slows the application, implies that the object is stored somewhere and may increase networks issues (if not stored localy)

4.使用查询参数(不推荐)

通过对对象进行字符串化:参见@Tahseen Quraishi 的回答

By stringyfing your object: See @Tahseen Quraishi's answer

只能传递很少的信息,网址很可怕

Only few informations can be passed and the URL is hideous

这里有一些例子

这篇关于Ionic 4 - 如何使用 navCtrl 或 Router 服务在页面之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆