Jeremy Thomas
Jeremy Thomas

Reputation: 6684

Angular 2: Importing shared functions

I find myself reusing generic functions and I'd much rather have them in one place and simply import them into my various components. Is that something I can do easily in Angular 2?

For example:

handleResponse(message) {
    let toast = this.toastCtrl.create({
        message: message,
        duration: 3000,
        position: 'top'
    });
    toast.present();
}

Where would I put it in order to be able to import this function and call it?

Upvotes: 1

Views: 1389

Answers (1)

joh04667
joh04667

Reputation: 7427

You can use a class to do this. The best way to do this is to create a class with static members so that you can access its properties without constructing the class. This is usually done in its own file.

Example:

export class Utils {

  public static handleResponse(): returnType {...}

  public static doAThing(): anotherType {...}

}

...and then import your Utils class as normal, then call its methods statically:

import { Utils } from 'path/to/utils';

...

let banana = Utils.handleResponse(thing);

Note that static members should be public (and need to be declared even though undeclared members are public by default).

Upvotes: 1

Related Questions