This might be a beginners question, the question is related to understanding why do we need injecting the services into components.
1] Why do we need to inject the service to each component when we could just create a static method and it will return the same output and we're really not going to need to keep writing extra code for injecting these services?
Let's say I have an authentication service like the one below with the normal convention:
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { GlobalConfig } from "../global-config";
// Models
import { UserModel } from "../models/user-model";
@Injectable()
export class AuthenticationService {
constructor(private http: Http) { }
authenticate(user: UserModel): Observable<UserModel> {
let userObject = this.http.post(GlobalConfig.getUrlFor('authentication'), user)
.map((response: Response) => {
let responseJSON = response.json();
let userObj = <UserModel>{
UserId: responseJSON.UserId,
FirstName: responseJSON.FirstName,
LastName: responseJSON.LastName,
FullName: responseJSON.FullName,
Email: responseJSON.Email,
UserName: responseJSON.UserName,
Password: responseJSON.Password
};
return userObj;
});
return userObject;
}
}
And in the view model, i would use it like that :
First: Inject the service
constructor(private authService: AuthenticationService) {}
Second: Call it
login() {
this.authService.authenticate(this.user)
.subscribe(
p => {
GlobalConfig.baseUser = p;
localStorage.setItem('user', JSON.stringify(p));
this.router.navigate(['/dashboard']);
},
e => {console.log('Error has Occured:', e); }
);
}
But If I in the first place made that authenticate method in the authentication service Static all I would have done is the following:
login() {
AuthenticationService.authenticate(this.user)
.subscribe(
p => {
GlobalConfig.baseUser = p;
localStorage.setItem('user', JSON.stringify(p));
this.router.navigate(['/dashboard']);
},
e => {console.log('Error has Occured:', e); }
);
}
And I wouldn't have needed to inject it or write in extra necessary work.
I know Service injection is the known good practice but I really don't understand why. Appreciate if someone would explain more to me.