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?

2
  • Possible duplicate of TypeScript static classes Commented May 9, 2017 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. Commented May 9, 2017 at 20:41

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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(){}
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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.