I have an angular 2 webpack project where I currently have some functions that are repeated throughout several components. I would like to inherit all of these components from a "master" class OR component (whichever works), in order to be able to call my functions from all my components that need them.
As an example, if I have a function foo in 3 different components:
foo(s: string){
console.log(s);
}
I would like you move this function to another file/class/components:
class parent{
foo(s: string){
console.log(s);
}
}
And having someway to call my foo function from my a given component. For instance:
class child{
constructor(){
foo("Hello");
}
}
How would I do this using Angular 2 / Typescript?
You can create
utils.ts
which contains all common funcitonsThen you can use as below
If you want to use inheritance it's the
extends
keyword:parent.class.ts
child.component.ts
http://plnkr.co/edit/iQfqphLCx62Qy5lYVJa5?p=preview
Note that any decorate information is lost, so don't apply it to the base class and expect that the children will have it.
That's pretty much it for using inheritance for these purposes. The other methods of a shared service or even a static class are also viable. It really depends on what you're trying to accomplish with them and what pattern best matches your use case.
You can create class which all methods are static
then, just import it where you want to use
I would use a service, here's a shortened example from one of my apps:
Then you can inject this service into anything, which is really useful and you keep things DRY.
You would simply inject it like so:
EDIT:
As @aalielfeky's answer says you could use static functions.
However, I would personally avoid static functions because they are borderline impossible to test properly as well as giving you hell once the time comes where you need to inject something in the constructor that is going to be used in one of the functions. Since static functions can't use anything that's injected.
Don't make the same mistake as me because you will end up having to rewrite a lot of code.