preface
Ionic3 makes it easy for the parent page to pass parameters to the parent page using navParams provided by the framework, but the reverse is not so easy because the pop function in the routing navController does not support passing parameters. It makes the previous method (on the surface is still useful, actually, a detailed look at the body), you need anything else at this time to achieve our goal, therefore, in this paper, we will face the parent page for page Ionic3 neutron transfer and problems with the commonly used several kinds of solutions, more if you have any question or suggestion, welcome to my colleagues below comments, make progress together!
Introduction to the
How do I communicate page-to-page in Ionic? There are three directions: route, event, and Service. Since the three directions have different implementations respectively, and each scheme ADAPTS to different scenarios, the following will compare these several schemes from the aspects of implementation, advantages and disadvantages, and adaptation scenarios, and finally you see what you need.
First, use routing to pass parameters
If you don’t know the Ionic3 routing value, please poke NavController to find out.
NavParams = navParams = navParams = navParams = navParams = navParams There are two scenarios
1. Pass “page”
// navContronller
// The syntax may not be correct, please correct it according to your own code<! -- Parent page -->public a = 'a';
navCtrl.push('childrenPage', {
parent: this}) <! --> parent = navparams.get ('parent');
parent.a = 'change from childe'; <! -- Parent page -->console.log(a) // change from childe
// You can also call the parent page's methods directly
Copy the code
Why does it work that way?
The history stack
Ionic3 routing has the concept of a history stack, which is the same operation as the stack. When the app starts at the root page, the history stack has only one page, which is your root page. After that, whenever you use navController’s push method to reach a new page, The history stack adds a new page and pops that page out of the history stack when it pops.
routing
Ionic3’s routing mechanism is “magical”, unlike other common vue-router or Angular single-page routing, which is a bit like a pseudo-route. Because all pages in the history stack actually exist on the current page, hee hee, the proof is shown below:
Analysis of the
Looking at the page code shows that each page is just an Angular component decorated with the InoicPage decorator, so you can change the state of the component by getting an instance of the component. Given the routing above, we know that our parent page or component is not destroyed (self-validating) even when we reach the child page. So in a child page, we can manipulate it by taking an instance of the history page. Finally we rearrange the idea: here use navParams to pass the parent page itself to the child page, and then the child page to obtain the parent page to operate on it, through this way to achieve the purpose of passing parameters.
advantages
It is simple and efficient. You can even bypass the step of passing parameters and directly operate on the child page to the parent page (not recommended).
disadvantages
- High degree of coupling between the father and son pages, the operation of the child page for the parent page is “invisible”, excessive use will cause maintenance difficulties, because you will need to always pay attention to the child page in front of the parent page.
- Multilevel page pass-throughs need to pass through multiple intermediate pages, even though they may not use the parent page, resulting in multiple pages passing unwanted parameters and code becoming bloated and difficult to maintain.
Recommended Scenarios
Scenarios involving less and less complex operations on the parent page, and only recommended between parent – > child, and you want to declare a clear parameter name to indicate the connection between the parent page, improve the maintainability of the code.
2. Pass the callback
<! Here is a common version on the Internet, but I don't like this version. -- Parent page -->public a = 'a';
// The arrow function must be used, otherwise this method will fail
public parentPromise = (childrenParams) = > new Promis((resolve, reject) = > {
// Here you can do whatever you want with the returned parameters
this.a = childrenParams;
console.log('childe change work: '.this.a);
resolve();
});
navCtrl.push('childrenPage', {
parentPromise: this.parentPromise }); <! ParentPromise = navparams.get (parentPromise = navparams.get ('parentPromise');
parentPromise('change from childe').then((a)= > {
// 此时会打印 childe change worke: change from childe
navCtrl.pop();
})
Copy the code
Preliminary knowledge
The code is a little convoluted here, but you need to know about Promise, arrow functions, TypeScript. If you don’t know Promise, arrow functions, and see what happens next.
Analysis of the
- ParentPromise:
- Take a parameter (typically passed in by a child page) and return a Promise
- Once a parameter is received internally within a Promise, it can be used to perform some action to end the Promise
- ParentPromise execution order for child pages:
- You pass in parameters, perform actions from the parent page in the child page, and then perform pop back to the parent page
ParentPromise: parentPromise: parentPromise: parentPromise: parentPromise: parentPromise: parentPromise The former is displayed to pass this to the child page, all the control is given to the child page, the latter is to use the arrow function to bind parentPromise’s this to the parent page, the control is on the parent page.
advantages
- Compared to the previous approach, this method reduces the coupling between parent and child pages and improves the maintainability of the code.
disadvantages
- Multiple hierarchies cannot be used efficiently.
- This method is a little harder to understand than the previous one.
I want to say
This code is problematic. It is not the result that is the problem, but the difference between the actual execution of the code and the expected execution of the code representation. When I tried to interpret parentPromise, I expected that the child page would pass in parameters — > the child page would return — > the parent page would get parameters and do relevant operations, but the actual execution behavior was not at all like the previous analysis: The parentPromise Promise inside the parentPromise is actually not very meaningful in the actual execution process. You can directly call back and perform the operation of POP in the child page. That’s why I don’t like this code very much. This paragraph below gives the author’s “improved version” for readers to comment.
<! -- Parent page -->public a = 'a';
// The arrow function can still be used
public popWithParams(childNavCtrl: navController, childeParams: any) {
// Go back to the parent page
childNavCtrl.pop().then(function() {
this.a = childrenParams;
console.log('childe change work: '.this.a); }}; navCtrl.push('childrenPage', {
popWithParams: this.popWithParams }); <! PopWithParams = navparams.get (popWithParams = navparams.get ('parentPromise');
popWithParams(navCtrl, 'change from childe');
Copy the code
3. Use this and callback
<! This method is a combination of the former two methods, and the second method is more like, but the use is simpler and easier to understand --> <! -- Parent page -->public a = 'a';
public parentCallback = (childeParams: any) = > {
// This is bound to the parent page
// Only if the code here is asynchronous (e.g., data requires Ajax retrieval), consider the use of method 2 to pass Promis
this.a = childrenParams;
console.log('childe change work: '.this.a);
};
navCtrl.push('childrenPage', {
parentCallback: this.parentCallback }); <! PopWithParams = navparams.get (popWithParams = navparams.get ('parentPromise');
parentCallback('change from childe');
navCtrl.pop()
Copy the code
advantages
Simple to use, easy to understand, and parent-child page coupling is relatively low control in the parent page.
disadvantages
Same as the first two.
Two, event transmission
1. Events provided by Ionic
<! -- Parent page -->constructor(public events: Events) {}
ngOnInit() {
// Subscribe to events from subpages
events.subscribe('childParams:doWhenInit'.(childParams) = > {
console.log(childParams); // params from childPage}); } <! -- Subpage -->constructor(public events: Events) {}
getParams() {
this.events.publish('childParams:doWhenInit'.'params from childPage');
}
Copy the code
Preliminary knowledge
This provides event support for Ionic, please poke Ionic Events for details.
advantages
- The idea is easy to understand, the child page publishes an event, the parent page subscribing to the event and processing.
- Parent and child page decoupling.
- Multilevel pages facilitate parameter transfer.
disadvantages
- Event names are difficult to manage. In complex applications, many event names need to be managed, which makes maintenance difficult.
- The subscriber, the parent page, needs to be manually unsubscribed, or it may be subscribed multiple times.
- When parameters are passed across pages, the subscriber, the parent page, needs to have generated and subscribed to the event at the time the event is published in order to receive the parameters.
2. The BehaviorSubject of RxJS is BehaviorSubject
3. Presents EventEmitter
Both of these methods need to be combined with Service. The ideas are similar to the Events provided in Ionic. There is no more research here.
Third, the Service
<! --pageParamsManagerService-->// Can be accessed and changed across the application
public a = 'no change'; <! -- Parent page -->import 'pageParamsManagerService' from './pageParamsManagerService'
constructor(public ppmService: pageParamsManagerService) {}
// Note that it cannot be placed in onInit or ionViewDidLoad hooks because the parent page is not destroyed when the child page is pushed and will not be executed when the pop comes back
ionViewWillEnter() {
// enter for the first time: no change;
// pop into: change from childePage
console.log(this.ppmService.a); } <! -- Subpage -->import 'pageParamsManagerService' from './pageParamsManagerService'
constructor(public ppmService: pageParamsManagerService) {
// Change the public variable
this.ppmService.a = 'change from childePage';
}
Copy the code
Preliminary knowledge
Angular applications have the concept of a Service. Services are typically singleton and accessible in application-wide scope (not discussed here), so we can use this feature for our parameter passing purposes.
advantages
- Easy to use.
- The pages are completely decoupled.
- Support multi-page access, and no page generation time requirements, multiple pages are fully decoupled.
disadvantages
- Because it is a singleton mode and needs to be introduced in app.module, it needs to do a good job of module management, here is another big pit, interested students can understand by themselves.
- If a fault occurs due to careless management, pay attention to the Service singleton.
- If there are few parameters and few operations, the introduction of a service just to pass in the parameters will appear bloated.
conclusion
We provide the corresponding parameter transmission scheme from the three directions of routing parameter transmission, event parameter transmission and service parameter transmission, and analyze their advantages and disadvantages and applicable scenarios. The author has limited ability, students who have more schemes are welcome to put forward in the comments, if you find any problems, also hope to give advice, thank you!!