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

查看:396
本文介绍了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和api的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 State(自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.使用服务和解析器

不会影响数据,但会有点沉重.

Does not fecth the data but a bit heavy.

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

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

只有很少的信息可以传递,URL令人毛骨悚然

Only few informations can be passed and the URL is hideous

此处有一些示例

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

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