Ionic 6和Angular导航至历史上已存在的路线

ttygqcqt  于 2022-12-08  发布在  Ionic
关注(0)|答案(1)|浏览(157)

I am using Ionic 6 and Angular 12 and I have couple pages in the app flow. I wen to page_4 and when I checked my DOM structure it looks like:

<ion-router-outlet>
    <page_1></page_1>
    <page_2></page_2>
    <page_3></page_3>
    <page_4></page_4>
</ion-router-outlet>

After page_4 I want to navigate to new page_2 and send some data via state object:

this.router.navigateByUrl('/page_2', { state: {dataHasChanged: true} });

I expected:

  1. Ionic will create again new <page_2></page_2> tag into DOM bellow <page_4></page_4>
  2. I can retrieve state data like I usually do:
this.router.getCurrentNavigation().extras?.state?.dataHasChanged

But result is different:

  1. App back to the previous <page_2></page_2> and my DOM structure looks like:
<ion-router-outlet>
    <page_1></page_1>
    <page_2></page_2>
</ion-router-outlet>
  1. this.router.getCurrentNavigation().extras is null and cannot see my data here. But I can see state data into windows.history.state object
    Can someone please explain me why this happened or at least refer me to some valuable documentation ?
mctunoxg

mctunoxg1#

If you enter a page that has already been loaded, it will not load again, or at least, not always. You can celar or update the content of the page inside ionViewWillEnter .
check this
add it in your page.ts

ionViewWillEnter() {
    ...
}

To solve the problem of navigation extras empty you can share data with a Service like this. It's not the cleanest way but it works

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataShareService {

  private __dataDict = {};

  setData(key: string, data: any) {
    this.__dataDict[key] = data;
  }
  getData(key: string) {
    return this.__dataDict[key];
  }

}

相关问题