I am little confused when is proper to use what.
1. Define class with static functions, just import and use imported name and then function
Shared class:
export class SomeClass {
static someFunction(){
...
}
}
Class which uses exported class:
import { SomeClass } from './someclassstatic'
...
constructor(){
SomeClass.someFunction()
}
2. Define standard class, then mount via DI
Shared class:
export class SomeClassDI {
public someFunctionDI(){
...
}
}
Class which uses exported class:
import { SomeClassDI } from './someclassdi'
...
constructor(private theclassdi:SomeClassDI){
this.theclassdi.someFunction()
}
3. Define standard class, then mount as provider while bootstraping
Shared class:
export class SomeClassBS {
public someFunctionBS(){
...
}
}
Class that bootstraps Angular2
import { SomeClassBS } from './someclassbs'
...
bootstrap(AppComponent, [SomeClassBS]);
Class which uses exported class:
??? I am not sure what can be the example here.
What is the proper use of the providers?
That is interesting question. First of all I advice you to read this article Dependency Injection in Angular 2
But if you are looking for briefly answer...
1.
If you will do like presented in your code, you will get an Error, because you do not create an instance of Class
but just trying to call function from constructor. You can rewrite this code, and it will works, but it is not great solution if you want to follow up Angular2 code style best practices.
import { SomeClass } from './someclassstatic'
...
constructor(){
let someClass = new SomeClass();
someClass.someFunction()
}
Just to make example of working code (You should not use this code)
2.
I believe that Angular2 will return you Error. Because you do not use DI pattern, just injection class but never register it. You will get something like this:
EXCEPTION: No provider for SomeClass! (AppComponent -> SomeClass)
So, probably you should not use this style of writing code too.
3.
Finally the best way is to use DI pattern, in your application. If you are going to use your service
just once in this component, you can just include it to providers
property of component annotation.
@Component({
selector: 'my-app',
templateUrl: 'app/app.partial.html',
providers: [SomeClass]
})
export class AppComponent {
constructor(private someClass: SomeClass) {
this.someClass.someFunction();
}
}
And if you are going to use your service
in the multiple different components, you can just inject
it on the Bootstrap phase of application, and you will not have to register it in the every component using providers
, you will need just to inject it in the constructor like in the example number 2, and there will not be an Error.
Hope it will help you!