Reputation: 2890
I'm struggling to share data between tabs in Ionic 4 / Angular 8 application.
And I have been looking all over the internet for solutions other than Subscribing to Observables but can't find any. to top everything, IonicFramework documentation doesn't have any note on that.
below is my basic settings
booking-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
}
I'm trying to share this.booking
variable with
any help will be appreciated
Upvotes: 2
Views: 1702
Reputation: 9235
You can do it in several ways, but I think in case of tabs the easiest is via shared service.
You can create a root scope service:
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class SharedService {
public variable1 = "Variable 1";
public variable2 = "Variable 2";
}
Then import it by every tabs page and do dependency injection for it:
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;
}
}
Now in your template code you can call to shared service vars:
<ion-header>
<ion-toolbar>
<ion-title>
Tab Three
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
{{ localVariable }}
{{ sharedService.variable2 }}
</ion-content>
Or just access values via shared service in all 3 tabs via ts file.
Here is stackblitz: https://stackblitz.com/edit/ionic-v4-angular-tabs-vmloya
Upvotes: 2