typescript 来自另一个控制器的 ionic 2 调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41196819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:05:31  来源:igfitidea点击:

ionic 2 call function from another controller

angulartypescriptionic2

提问by Mahmoud Ismail

I need to callfunctionin another controllerin ionic 2, it is possible?

我需要调用function另一个控制器ionic 2,这是可能的吗?

below my code and i want to call loadPeoplein tab controller.

在我的代码下方,我想调用loadPeople选项卡控制器。

home.ts

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

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.tsi want to call loadPeoplefunction on tab selected, how i can do this ?

tabs.ts 中,我想loadPeople选定的选项卡上调用函数,我该怎么做?

回答by Onno

There are several options. One way is to put your function loadPeople()into a service class, which is accessible from all components.

有几种选择。一种方法是将您的函数loadPeople()放入一个服务类中该类可从所有组件访问。

Another way is to use Ionic Eventsto 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:

另一种方法是使用Ionic Events来触发组件之间的函数调用。例如,如果选择一个选项卡调用一个函数tabSelected(),你可以在这个函数中触发一个事件:

tabSelected() {
  this.events.publish('functionCall:tabSelected', anyAdditionalData);
}

and listen to it in home.tsand call loadPeople()if the event has been fired:

并收听它home.tsloadPeople()在事件被触发时调用:

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

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

您甚至可以随事件发送数据(此处:)anyAdditionalData

回答by AishApp

All you need to do is to define the function as staticand call the function with class name.

您需要做的就是将函数定义为静态并使用类名调用该函数。

eg:

例如:

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

class B{
  classA.f1();
}

Hope it will work

希望它会起作用