简体   繁体   English

Angular:服务注入与打字稿静态方法

[英]Angular : Service Injection vs Typescript Static Methods

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? 1]当我们只能创建一个静态方法时,为什么我们需要将服务注入每个组件,它将返回相同的输出,我们真的不需要继续编写额外的代码来注入这些服务?

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. 感谢有人会向我解释更多。

Dependency injection provides much more flexibility and makes your application parts more independent. 依赖注入提供了更大的灵活性,使您的应用程序部件更加独立。 One case where I personally was burnt by static method — I developed a library and some projects made of multiple sub projects used different minor versions of my lib. 我个人被静态方法烧毁的一个案例 - 我开发了一个库,一些由多个子项目组成的项目使用了我的lib的不同次要版本。 There were no breaking changes between those and dependency injection would work just fine, injecting the first injectable that Angular picked up, however static method is defined on a specific class so you end up with 2 different methods from 2 different versions. 这些之间没有重大变化,依赖注入也可以正常工作,注入Angular选择的第一个注入,但静态方法是在特定类上定义的,所以最终得到2个不同版本的2种不同方法。

One very helpful feature of dependency injection is tokens — you can provide different things to different places that suit specific needs but all follow particular interface. 依赖注入的一个非常有用的功能是令牌 - 您可以为不同的地方提供不同的东西,以满足特定的需求,但都遵循特定的界面。 Example being custom controls with ControlValueAccessor or abstractions that combine multiple components — if you want to create a directive that you can use with multiple components you can do so by injecting a token in it and providing that token inside all suitable components of yours. 示例是使用ControlValueAccessor的自定义控件或组合多个组件的抽象 - 如果要创建可以与多个组件一起使用的指令,可以通过在其中注入令牌并在您的所有合适组件中提供该令牌来实现。

Overall, there is plenty of neat features in dependency injection that are just not possible by plain static methods and static methods have drawbacks. 总的来说,依赖注入有很多简洁的功能,而普通的静态方法是不可能的,而静态方法也有缺点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM