I need to call function
in another controller in ionic 2
, it is possible?
below my code and i want to call loadPeople
in tab controller.
home.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {PeopleService} from '../../providers/people-service/people-service';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,public peopleService: PeopleService) {
this.loadPeople();
}
loadPeople(){
this.peopleService.load()
.then(data => {
this.people = data;
});
}
}
tabs.ts
import { Component } from '@angular/core';
import { HomePage } from '../home/home';
import { AboutPage } from '../about/about';
import { ContactPage } from '../contact/contact';
@Component({
templateUrl: 'tabs.html'
})
export class TabsPage {
// this tells the tabs component which Pages
// should be each tab's root Page
tab1Root: any = HomePage;
tab2Root: any = AboutPage;
tab3Root: any = ContactPage;
constructor() {
}
}
in tabs.ts i want to call loadPeople
function on tab selected , how i can do this ?
There are several options. One way is to put your function loadPeople()
into a service class, which is accessible from all components.
Another way is to use Ionic Events to trigger function calls between components. For example, if the selection of a tab calls a function tabSelected()
, you can fire an event in this function:
tabSelected() {
this.events.publish('functionCall:tabSelected', anyAdditionalData);
}
and listen to it in home.ts
and call loadPeople()
if the event has been fired:
this.events.subscribe('functionCall:tabSelected', eventData => {
this.loadPeople();
});
You can even send data with the event (here: anyAdditionalData
).
All you need to do is to define the function as static and call the function with class name.
eg:
class A{
static f1(){
console.log("funtion1");
}
}
class B{
classA.f1();
}
Hope it will work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With