简体   繁体   中英

Ionic 4 How to get data from another page

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM