Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ionic 2 call function from another controller

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 ?

like image 728
Mahmoud Ismail Avatar asked Dec 17 '16 08:12

Mahmoud Ismail


2 Answers

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).

like image 174
Onno Avatar answered Oct 20 '22 00:10

Onno


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

like image 43
AishApp Avatar answered Oct 20 '22 01:10

AishApp