简体   繁体   English

TypeScript类中的工作注入如何进行?

[英]How does work injection in TypeScript Class?

There is the following TypeScript class: 有以下TypeScript类:

class RaceList {
    raceService: RaceService;
    races: Array<string>;

    constructor(raceService: RaceService) {
        // the interesting part is `: RaceService`
        this.raceService = raceService;
        this.raceService.list()
            .then(races => this.races = races);
      }
}

How does work this construction: this.raceService.list() if I dont have initialization of class like this: raceService = new RaceService() ? 如何构造这种结构: this.raceService.list()如果我没有像这样的类初始化: raceService = new RaceService()

To quote this tutorial: 引用教程:

"An Angular 2 service is simply a javascript function, along with its associated properties and methods, that can be included (via dependency injection) into Angular 2 components. They allow you to develop code for specific tasks that can be used in those components." “ Angular 2服务只是一个javascript函数及其相关的属性和方法,可以(通过依赖项注入)包含在Angular 2组件中。它们使您可以为可在这些组件中使用的特定任务开发代码。 ”

They do not require initialization when injected (it is done on its own), they have a single state and simply require to be injected in a given component. 它们在注入时不需要初始化(它自己完成),它们只有一个状态,只需要注入给定的组件即可。

Here's a better approach: 这是一个更好的方法:

class RaceList {
    races: Array<string>;

    constructor(private raceService: RaceService) {          
        raceService.list()
            .then(races => this.races = races);
    }
}

As you can see you do not need to save the service's value in a class variable as it is set to private, it can be used in any method in RaceList by calling this.raceService . 如您所见,由于将服务的值设置为private,因此无需将其保存在类变量中,可以通过调用this.raceService将其用于RaceList中的任何方法。

This is a syntactic sugar of typescript, Instead of: 这是打字稿的语法糖,而不是:

private raceService: RaceService;

constructor() {
    this.raceService = new RaceService;
}

You simply do this: 您只需执行以下操作:

constructor(private raceService: RaceService) {}

Under the hood, Angular does the initialization and give you the initialized instance through your component's constructor. 在幕后,Angular进行初始化,并通过组件的构造函数为您提供已初始化的实例。

If your service itself needs some others services in its constructor, Angular initializes this others services, provide them to your service constructor, and then provide your service to your component. 如果您的服务本身在其构造函数中需要其他服务,则Angular会初始化该其他服务,将其提供给服务构造函数,然后将您的服务提供给组件。

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

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