Angular2中的提供程序是什么? [英] What are providers in Angular2?

查看:93
本文介绍了Angular2中的提供程序是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular2组件配置中,providers是我们可以指定的键之一.这些提供者的定义方式以及用途是什么?

In the Angular2 component configuration providers is one of the keys that we could specify. How are these providers defined and what are they used for?

@Component({
  ..
  providers: [..],
  ..
})

注意:

Angular2文档正在逐渐成熟,但仍然很少.当前,它将提供者定义为:

Angular2 documentation is gradually maturing but still sparse. It currently defines providers as:

一系列依赖注入提供程序,用于 组件要求.

An array of dependency injection providers for services that the component requires.

此递归定义不是很有帮助.带有示例的更详细的说明确实会有所帮助.

This recursive definition isn't very helpful. A more detailed explanation with an example would really help.

推荐答案

提供程序通常是单例(一个实例)对象,其他对象可以通过依赖项注入(DI)访问.

Providers are usually singleton (one instance) objects, that other objects have access to through dependency injection (DI).

如果您打算多次使用一个对象,例如在不同组件中使用Http服务,则可以要求该服务的相同实例(重用它).您可以在DI的帮助下,通过提供对DI为您创建的同一对象的引用.

If you plan to use an object multiple times, for example Http service in different components, you can ask for same instance of that service (reuse it). You do that with the help of DI by providing a reference to the same object that DI creates for you.

@Component){
  ..
  providers: [Http]
}

..而不是每次都创建新对象:

..instead of creating new object every time:

@Component){}
class Cmp {
  constructor() {
    // this is pseudo code, doens't work
    this.http = new Http(...options);
  }
}

这是一个近似值,但这是依赖注入背后的一般思想-让框架处理创建和维护可重用对象... Provider 是Angular用于这些可重用对象(依赖项)的术语.

This is an approximation, but that's the general idea behind Dependency Injection - let the framework handle creation and maintenance of reusable objects... Provider is Angular's term for these reusable objects (dependencies).

这篇关于Angular2中的提供程序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆