1

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?

Jeremy Thomas
  • 6,240
  • 9
  • 47
  • 92
  • Possible duplicate of [TypeScript static classes](http://stackoverflow.com/questions/13212521/typescript-static-classes) – Ahmed Musallam May 09 '17 at 20:22
  • Usually I create a shared component and put *shared* `functions` in this class, so I can easily use in other components extending the shared component or even *injecting* the *shared* `component` in another component. – developer033 May 09 '17 at 20:41

1 Answers1

1

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

joh04667
  • 7,159
  • 27
  • 34
  • will this work if I need to import something like `ViewController` into the utility class? If yes, how can I declare it without using `constructor(){}` – Jeremy Thomas May 10 '17 at 12:55
  • If something needs to be injected by Angular, it *needs* to be in the constructor, unfortunately. This is the basis for how dependency injection / tokens work in the Angular compiler. Might I suggest adding the utility methods to the service itself? If multiple services need the methods, you could write a base class with the methods and have those services extend that base class (using `extends` and with no static methods) – joh04667 May 10 '17 at 16:57