Ionic call function 2 from another controller

I need to call function in another controller in ionic 2 , maybe?

below my code, and I want to call loadPeople in the 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 root Page tab1Root: any = HomePage; tab2Root: any = AboutPage; tab3Root: any = ContactPage; constructor() { } } 

in tabs.ts I want to call the loadPeople function on the tab selected , how can I do this?

+6
source share
2 answers

There are several options. One way is to add the loadPeople() function to a class accessible from all components.

Another way is to use Ionic Events to trigger function calls between components. For example, if selecting a tab calls the tabSelected() function, 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 was fired:

 this.events.subscribe('functionCall:tabSelected', eventData => { this.loadPeople(); }); 

You can even send data with an event (here: anyAdditionalData ).

+11
source

All you have to do is define the function as static and call the function with the class name.

eg:

 class A{ static f1(){ console.log("funtion1"); } } class B{ classA.f1(); } 

Hope it works

+2
source

Source: https://habr.com/ru/post/1013238/


All Articles