如何在不知道用户来自哪个页面的情况下向后导航,返回一些数据

How to navigate back, returning some data, without knowing which page the user came from

我有一个页面可以被多个 "parent/origin" 页面导航到。

像这样:

Page 1 \
        \
Page 2 -- Page 4
        /
Page 3 /

我需要 return 从第 4 页到它的父页面(原始页面)的一些数据。

我一直在使用 this.navCtrl.back() 返回应用程序的其余部分,但这次我需要 return 一些数据,似乎无法使用此功能。

我知道可以使用 this.navCtrl.navigateBack(['page-1'], extras) 传递数据,但我需要知道用户来自哪个页面。有什么简单的方法可以做到这一点吗?

我知道我可以在转到第 4 页时在 extras 上传递原始页面的名称,但它似乎不太正确(您的意见是什么?)。

提前致谢。

正如我在评论中所说,这看起来是使用 modals 的完美场景。这样 Page 4 就可以 return 向调用者发送数据,即使不知道哪个页面有 created/presented 它。

代码可能是这样的:

第 1 页/第 2 页/第 3 页:

// Angular
import { Component } from '@angular/core';

// Ionic
import { ModalController, OverlayEventDetail } from '@ionic/angular';

// Modal page
import { ModalPage } from '../modal/modal.page';

@Component({ ... })
export class ModalExample {
  constructor(public modalController: ModalController) {}

  async presentModal() {
    // create the modal
    const modal = await this.modalController.create({
        component: ModalPage,
        componentProps: {
            'firstName': 'Douglas',
            'lastName': 'Adams',
            'middleInitial': 'N'
        }
    });

    // handle the data returned by the modal
    modal.onDidDismiss().then((detail: OverlayEventDetail) => {
      if (detail !== null) {
        console.log('The result: ', detail.data);
      }
    });

    // present the modal
    return await modal.present();
  }
}

第 4 页

// Angular
import { Component, Input } from '@angular/core';

// Ionic
import { NavParams } from '@ionic/angular';

@Component({ ... })
export class ModalPage {

  // Data passed in by componentProps
  @Input() firstName: string;
  @Input() lastName: string;
  @Input() middleInitial: string;

  constructor(navParams: NavParams) {
    // componentProps can also be accessed at construction time using NavParams
    console.log(navParams.get('firstName');
  }

  dismiss() {
    // using the injected ModalController this page
    // can "dismiss" itself and optionally pass back data
    this.modalCtrl.dismiss({
      'dismissed': true
    });
  }
}

请务必阅读 Ionic 文档中的 lazy loading section 以了解模式页面应如何由将要使用它的页面导入。

已经在向前导航时将原点作为额外内容传递 - 然后它将在第 4 页上已知,并且可用于 return 特定页面的额外内容。它非常简单,不需要模态对话框解决方法,而这并不是我们所要求的。