Ionic 4 How to get data from another page

谁说我不能喝 提交于 2020-01-04 11:10:51

问题


I'm navigating page and send data to page. i want to know how can i get data i send to the page ? .

Example: In ionic 3 we push page and send data like this

this.navCtrl.push(Page, {x:x})

And in other page we get date from navParams like

this.navParams.get('x');

I need to know how ill get data in ionic 4 ? Im navigating page and data like this

details(y){
 this.navCtrl.navigateForward('/packagedetails',{y:y});
}

回答1:


You can use navigaionExtras to achieve this

page1:

  let navigationExtras: NavigationExtras = {
          state: {
            x: x
          }
        };
        this.router.navigate(['details'], navigationExtras);

page2:

  constructor(private route: ActivatedRoute, private router: Router) {
        this.route.queryParams.subscribe(params => {
          if (this.router.getCurrentNavigation().extras.state) {
            this.data = this.router.getCurrentNavigation().extras.state.x;
          }
        });
      }



回答2:


They are many way to do it. Here is three:

First

This is a one page parameter to another, but nothing is saved if the user close the app (not sure at 100%, but if I remember well it isn't):

page 1:

import {Router} from "@angular/router" 

@Component(thingsThatIsIt)

export class Page1Page{
  constructor(private router: Router,OthersThingsInYourConstructor){thingsThatIsIt} 


  FunctionToGoOnPage2(someParameters) //someParameters is an JS object (like JSON for exemple)
  {
    this.router.navigate(["Page2",someParameters])
  }
}

page 2:

import {ActivatedRoute} from "@angular/router" 

@Component(thingsThatIsIt)

export class Page2Page{
  constructor(private route: ActivatedRoute,OthersThingsInYourConstructor)
  {
    this.route.params.subscribe(params => {
      console.log(params)
      FunctionThatDealWithParameters(params)
    })
  }




  FunctionThatDealWithParameters(someParameters) //someParameters is an JS object (like JSON for exemple)
  {
    //code to use your parameters
  }
}

Second

This is a one page to many others, but nothing is saved if the user close the app:

make a service: ionic generate service

in this service, create some attributes, and some get and set method.

in a page that need your service, for getting or setting method, you just have to import it, and call your get/set method (the one you need by the way)

Third

This is a one page to many others, and everything is save, even if the user close his app:

use the ionic local storage



来源:https://stackoverflow.com/questions/56415132/ionic-4-how-to-get-data-from-another-page

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