How to invoke a function from a different controller in Ionic 2

Is it possible to call a function in another controller within Ionic 2? Here is my code where I want to call the loadPeople function 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's root Page
tab1Root: any = HomePage;
tab2Root: any = AboutPage;
tab3Root: any = ContactPage;

constructor() {

}
}

In tabs.ts, how can I call the loadPeople function when a tab is selected?

Answer №1

If you're looking for different approaches, there are a few options available. One option is to move your function loadPeople() into a service class, making it accessible from all components.

Another alternative is to utilize Ionic Events to trigger function calls between components. For instance, if selecting a tab triggers the function tabSelected(), you can generate an event within this function:


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

You can then listen for this event in home.ts and invoke loadPeople() when the event is detected:


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

Additionally, you have the option to include data with the event (e.g., anyAdditionalData).

Answer №2

To make this work, simply declare the function as static and invoke it using the class name.

For example:

class Alpha{
 static func1(){
  console.log("function one");
 }
}

class Beta{
  Alpha.func1();
}

Give it a try and hopefully it will run smoothly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Angular2 (Frontend) and Spring Boot (Backend) for Excel file uploading

As someone who is new to Angular 2, I am currently attempting to upload an Excel file from the Angular 2 frontend. My goal is to upload the Excel file from the Angular 2 frontend, send it to the Spring Boot backend for necessary modifications, and th ...

Issue: the module '@raruto/leaflet-elevation' does not include the expected export 'control' as imported under the alias 'L' . This results in an error message indicating the absence of exports within the module

Looking for guidance on adding a custom Leaflet package to my Angular application called "leaflet-elevation". The package can be found at: https://github.com/Raruto/leaflet-elevation I have attempted to integrate it by running the command: npm i @raruto/ ...

Leveraging Express for delegating requests to an ADFS server

We are currently facing a challenge with authenticating to our on-premise ADFS 3.0 server. Our Angular application, a single-page app, needs to authenticate with the ADFS server. However, we are encountering CORS issues due to them not being on the same se ...

An issue has occurred in Vue3 where the argument type 'typeof import("../dist/vue")' cannot be assigned to the parameter type 'PublicAPIComponent'

I recently installed Vue using the CLI version 4.4.1. Following that, I executed the command 'vue add vue-next' to update to Vue3. However, upon opening 'main.ts', I encountered a Typescript error: Argument of type 'typeof impor ...

Invoke a function upon subscription in Angular

I have a requirement to trigger a method after a window resize event, but with a 500ms delay. I have implemented it as shown below and it seems to be working fine. However, being new to Angular, I am curious to know if there is a better way to achieve th ...

Retrieve information using an asynchronous pipeline once the screen is fully loaded

In my table component, I have integrated functionality for data reloading and filtering. These actions are powered by Subjects: private fetchFromServer$ = new Subject< void >(); private filter$ = new Subject< void >(); The data fetching proces ...

Creating an object type that includes boolean values, ensuring that at least one of them is true

To ensure both AgeDivisions and EventStyles have at least one true value, I need to create a unique type for each. These are the types: type AgeDivisions = { youth: boolean; middleSchool: boolean; highSchool: boolean; college: boolean; open: bo ...

How do I adjust brightness and contrast filters on a base64 URL?

When presented with an image in base64 format like this: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDAAwfqNRk/rjcYX+PxrV/wtWqwJSTlboMgAAAABJRU5ErkJggg== What is the most efficient method to programmatically alter a filter (such as brightness or cont ...

Programmatically click a button from the library by triggering a click on its outer div using Angular

Currently, I'm just starting out with Angular. I've been using the @abacritt/angularx-social-login package and noticed that the Google button it provides is only an icon. I'd like to customize its appearance by placing the icon inside a div ...

Executing the command `subprocess.run("npx prettier --write test.ts", shell=True)` fails to work, however, the same command runs successfully when entered directly into the terminal

Here is the structure of my files: test.py test.ts I am currently trying to format the TypeScript file using a Python script, specifically running it in Command Prompt on Windows. When I execute my python script with subprocess.run("npx prettier --w ...

Issue: Catching errors in proxy function calls

I am currently using Vue 3 along with the latest Quasar Framework. To simplify my API calls, I created an Api class as a wrapper for Axios with various methods such as get, post, etc. Now, I need to intercept these method calls. In order to achieve this ...

Accessing environment-based constants in TypeScript beyond the scope of Cypress.env()Is there a way to gain access to environment-specific constants

Imagine I have an API test and the URL and Credentials are different between production and development environments: before("Authenticate with auth token", async () => { await spec().post(`${baseUrl}/auth`) .withBody( { ...

Dynamic Object properties are not included in type inference for Object.fromEntries()

Hey there, I've been experimenting with dynamically generating styles using material UI's makeStyles(). However, I've run into an issue where the type isn't being correctly inferred when I use Object.fromEntries. import * as React from ...

Why is it necessary to include a dollar sign before interpolation in Angular?

While diving into a tutorial, I stumbled upon a piece of code that piqued my curiosity. I grasped the concept that appending a dollar sign as a suffix indicates observability, but I wonder why the dollar sign was also prefixed to this.log(`updated hero i ...

Linking enumeration value to an Angular material table

Is it possible to associate enum values with an Angular Material table? For instance, I have defined an enum: export enum EnumName { val1 = 1, val2 = 2, val3 = 3 } and I want the Angular Material table to display it like this: Id EnumNameColumn ...

Converting a string value into an object in Javascript using a command that functions similarly to eval in Python

When working with Python, the stringValue variable is often assigned as a string: stringValue = '{"DATA":{"VERSION":1.1, "STATE":True, "STATUS":"ONLINE"}}' To convert this string into a Python di ...

Scheduled task for sending emails using NodeJS

Currently working on my debut Node + Express app (MEAN) and seeking to integrate automatic email sending feature. Idea is for users to set reminders that the mailer will dispatch on specified dates. Considering incorporating the default Nodemailer + Node ...

Using React Material UI in VSCode with TypeScript significantly hampers autocompletion speed

When including the "@mui/material", Visual Studio Code may become unresponsive, leading to Typescript warnings appearing after 10-15 seconds instead of the usual less than 10 milliseconds. For example: import { Button } from '@mui/material&a ...

Creating Beautiful MDX Layouts with Chakra UI

Currently, I am attempting to customize markdown files using Chakra UI within a next.js application. To achieve this, I have crafted the subsequent MDXComponents.tsx file: import { chakra } from "@chakra-ui/react" const MDXComponents = { p: (p ...

Utilize the express library (NodeJS, TypeScript) to send back the results of my function

I am curious about how I can handle the return values of my functions in my replies. In this specific scenario, I am interested in returning any validator errors in my response if they exist. Take a look at my SqlCompanyRepository.ts: async create(compan ...