Angular : Service Injection vs Typescript Static Methods -


this might beginners question, question related understanding why need injecting services components.

1] why need inject service each component when create static method , return same output , we're not going need keep writing code injecting these services?

let's have authentication service 1 below normal convention:

import { injectable } '@angular/core'; import { http, response, headers } '@angular/http'; import { observable } 'rxjs/rx'; import 'rxjs/add/operator/map';  import { globalconfig } "../global-config";  // models import { usermodel } "../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 view model, use :

first: inject 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 in first place made authenticate method in authentication service static have done 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 wouldn't have needed inject or write in necessary work.

i know service injection known practice don't understand why. appreciate if explain more me.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -