Ionic 4 在选项卡之间共享数据

Ionic 4 share data between tabs

我很难在 Ionic 4 / Angular 8 应用程序的选项卡之间共享数据。

我一直在 Internet 上寻找除订阅 Observables 之外的解决方案,但找不到任何解决方案。最重要的是,IonicFramework 文档对此没有任何说明。

下面是我的基本设置

预订-routing.module.ts

const routes: Routes = [
    {
        path: 'booking',
        component: BookingPage,
        children: [
            {
                path: 'detail',
                children: [
                    {
                        path: '',
                        loadChildren: () => import('./detail/detail.module').then((m) => m.DetailPageModule)
                    }
                ]
            },
            {
                path: 'tracking',
                children: [
                    {
                        path: '',
                        loadChildren: () => import('./tracking/tracking.module').then((m) => m.TrackingPageModule)
                    }
                ]
            },
            {
                path: 'pass',
                children: [
                    {
                        path: '',
                        loadChildren: () => import('./pass/pass.module').then((m) => m.PassPageModule)
                    }
                ]
            },
            {
                path: '',
                redirectTo: 'booking/detail',
                pathMatch: 'full'
            }
        ]
    },
    {
        path: '',
        redirectTo: 'booking/detail',
        pathMatch: 'full'
    }
];

booking.html

<ion-tabs>
    <ion-tab-bar slot="bottom">
      <ion-tab-button tab="detail">
        <ion-label>Details</ion-label>
      </ion-tab-button>

      <ion-tab-button tab="tracking">
        <ion-label>Tracking</ion-label>
      </ion-tab-button>

      <ion-tab-button tab="pass">
        <ion-label>Pass</ion-label>
      </ion-tab-button>
    </ion-tab-bar>
  </ion-tabs>

booking.ts

booking: Booking;

constructor() {
    this.booking = someValue
}

我正在尝试与

共享 this.booking 变量

任何帮助将不胜感激

您可以在 several ways 中完成,但我认为对于选项卡,最简单的方法是通过共享服务。

您可以创建根范围服务:

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

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

    public variable1 = "Variable 1";
    public variable2 = "Variable 2";

}

然后在每个tabs页面导入并做依赖注入:

import { Component } from '@angular/core';
// import it first:
import { SharedService } from '../services/shared.service';

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page {

  localVariable: string;

  constructor(
    // inject as dependency:
    private sharedService: SharedService
  ) {
    this.localVariable = this.sharedService.variable1;
  }

}

现在在您的模板代码中,您可以调用共享服务变量:

<ion-header>
  <ion-toolbar>
    <ion-title>
      Tab Three
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  {{ localVariable }}
  {{ sharedService.variable2 }}
</ion-content>

或者仅通过 ts 文件在所有 3 个选项卡中通过共享服务访问值。

这里是 stackblitz: https://stackblitz.com/edit/ionic-v4-angular-tabs-vmloya