新用户注册入口 老用户登录入口

[转载]MULTI PROVIDERS IN ANGULAR 2

文章作者:转载 更新时间:2023-03-31 11:22:56 阅读数量:525
文章标签:TokenHooks
本文摘要:Angular 2的依赖注入系统中引入了“Multi Providers”特性,允许开发者根据应用需求接入并扩展特定操作的自定义功能。本文阐述了Multi Providers的外观、工作原理及其在保持Angular平台灵活性与可扩展性上的作用。回顾知识点,Provider是一种描述如何创建特定类型对象的指令,如为DataService配置Provider,则可让Angular知晓如何创建和注入该服务。而Multi Providers的独特之处在于,它允许针对单个Token提供多个依赖项,通过设置`multi: true`选项实现对同一接口的扩展或覆盖,如Angular内部使用的验证器插件机制。此外,还应注意Multi Providers不能与常规Provider混用。这一特性使得诸如NG_VALIDATORS之类的多提供者能够在Angular平台上实现灵活且可扩展的自定义挂钩功能。
转载文章

本篇文章为转载内容。原文链接:https://blog.csdn.net/u011153667/article/details/52483856。

该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。

作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。

如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。

The new dependency injection system in Angular 2 comes with a feature called “Multi Providers” that basically enable us, the consumer of the platform, to hook into certain operations and plug in custom functionality we might need in our application use case. We’re going to discuss what they look like, how they work and how Angular itself takes advantage of them to keep the platform flexible and extendible.

Recap: What is a provider?

If you’ve read our article on Dependency Injection in Angular2 you can probably skip this section, as you’re familiar with the provider terminology, how they work, and how they relate to actual dependencies being injected. If you haven’t read about providers yet, here’s a quick recap.

A provider is an instruction that describes how an object for a certain token is created.

Quick example: In an Angular 2 component we might have a DataService dependency, which we can ask for like this:

import { DataService } from './data.service';@Component(...)
class AppComponent {constructor(dataService: DataService) {// dataService instanceof DataService === true}
}

We import the type of the dependency we’re asking for, and annotate our dependency argument with it in our component’s constructor. Angular knows how to create and inject an object of type DataService, if we configure a provider for it. This can happen either on the application module, that bootstrap our app, or in the component itself (both ways have different implications on the dependency’s life cycle and availability).

// application module
@NgModule({...providers: [{ provide: DataService, useClass DataService }]
})
...// or in component
@Component({...providers: [{ provide: DataService, useClass: DataService }]
})
class AppComponent { }

In fact, there’s a shorthand syntax we can use if the instruction is useClass and the value of it the same as the token, which is the case in this particular provider:

@NgModule({...providers: [DataService]
})
...// or in component
@Component({...providers: [DataService]
})
class AppComponent { }

Now, whenever we ask for a dependency of type DataService, Angular knows how to create an object for it.

Understanding Multi Providers

With multi providers, we can basically provide multiple dependencies for a single token. Let’s see what that looks like. The following code manually creates an injector with multi providers:

const SOME_TOKEN: OpaqueToken = new OpaqueToken('SomeToken');var injector = ReflectiveInjector.resolveAndCreate([{ provide: SOME_TOKEN, useValue: 'dependency one', multi: true },{ provide: SOME_TOKEN, useValue: 'dependency two', multi: true }
]);var dependencies = injector.get(SOME_TOKEN);
// dependencies == ['dependency one', 'dependency two']

Note: We usually don’t create injectors manually when building Angular 2 applications since the platform takes care of that for us. This is really just for demonstration purposes.

A token can be either a string or a type. We use a string, because we don’t want to create classes to represent a string value in DI. However, to provide better error messages in case something goes wrong, we can create our string token using OpaqueToken. We don’t have to worry about this too much now. The interesting part is where we’re registering our providers using the multi: true option.

Using multi: true tells Angular that the provider is a multi provider. As mentioned earlier, with multi providers, we can provide multiple values for a single token in DI. That’s exactly what we’re doing. We have two providers, both have the same token but they provide different values. If we ask for a dependency for that token, what we get is a list of all registered and provided values.

Okay understood, but why?

Alright, fine. We can provide multiple values for a single token. But why in hell would we do this? Where is this useful? Good question!

Usually, when we register multiple providers with the same token, the last one wins. For example, if we take a look at the following code, only TurboEngine gets injected because it’s provider has been registered at last:

class Engine { }
class TurboEngine { }var injector = ReflectiveInjector.resolveAndCreate([{ provide: Engine, useClass: Engine},{ provide: Engine, useClass: TurboEngine}
]);var engine = injector.get(Engine);
// engine instanceof TurboEngine

This means, with multi providers we can basically extend the thing that is being injected for a particular token. Angular uses this mechanism to provide pluggable hooks.

One of these hooks for example are validators. When creating a validator, we need to add it to the NG_VALIDATORS multi provider, so Angular picks it up when needed

@Directive({selector: '[customValidator][ngModel]',providers: [provide: NG_VALIDATORS,useValue: (formControl) => {// validation happens here},multi: true]
})
class CustomValidator {}

Multi providers also can’t be mixed with normal providers. This makes sense since we either extend or override a provider for a token.

Other Multi Providers

The Angular platform comes with a couple more multi providers that we can extend with our custom code. At the time of writing these were

  • NG_VALIDATORS - Interface that can be implemented by classes that can act as validators
  • NG_ASYNC_VALIDATORS - Token that can be implemented by classes that can act as async validators

Conclusion

Multi providers are a very nice feature to implement pluggable interface that can be extended from the outside world. The only “downside” I can see is that multi providers only as powerful as what the platform provides. NG_VALIDATORS and NG_ASYNC_VALIDATORS are implemented right into the platform, which is the only reason we can take advantage of those particular multi providers. There’s no way we can introduce our own custom multi providers (with a specific token) that influences what the platform does, but maybe this is also not needed.


原文链接:http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html

本篇文章为转载内容。原文链接:https://blog.csdn.net/u011153667/article/details/52483856。

该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。

作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。

如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。

相关阅读
文章标题:[转载][洛谷P1082]同余方程

更新时间:2023-02-18
[转载][洛谷P1082]同余方程
文章标题:[转载]webpack优化之HappyPack实战

更新时间:2023-08-07
[转载]webpack优化之HappyPack实战
文章标题:[转载]oracle 同时更新多表,在Oracle数据库中同时更新两张表的简单方法

更新时间:2023-09-10
[转载]oracle 同时更新多表,在Oracle数据库中同时更新两张表的简单方法
文章标题:[转载][Unity] 包括场景互动与射击要素的俯视角闯关游戏Demo

更新时间:2024-03-11
[转载][Unity] 包括场景互动与射击要素的俯视角闯关游戏Demo
文章标题:[转载]程序员也分三六九等?等级差异,一个看不起一个!

更新时间:2024-05-10
[转载]程序员也分三六九等?等级差异,一个看不起一个!
文章标题:[转载]海贼王 动漫 全集目录 分章节 精彩打斗剧集

更新时间:2024-01-12
[转载]海贼王 动漫 全集目录 分章节 精彩打斗剧集
延伸阅读
作为当前文章的延伸阅读,仅对当前文章有效。
在进一步理解Angular 2的“Multi Providers”特性后,我们可以深入探索其在现代前端开发中的实际应用与最新进展。近年来,随着Angular生态系统的不断演进,Multi Providers的使用场景更加丰富多元。例如,在Angular 13版本中,开发者可以利用Multi Providers为应用程序添加自定义转换器(如HTTP拦截器、路由守卫等),实现对请求和响应数据的统一处理。
同时,结合最新的Angular Ivy编译器,Multi Providers在性能优化方面也发挥了重要作用,特别是在懒加载模块时动态注入服务以减少初始加载时间。此外,一些社区项目如NgRx Store库也巧妙运用了Multi Provider机制,允许开发者注册多个Reducer来管理状态树,从而实现更为复杂的应用状态管理逻辑。
另外,为了帮助开发者更好地理解和掌握这一特性,Angular团队及社区专家们提供了许多深入解读的文章和教程,通过实例演示如何在实践中合理运用Multi Providers进行功能扩展和模块化设计。这些资源不仅涵盖了基础用法,还探讨了高级应用场景及其背后的设计理念,对于提升Angular项目架构水平具有重要意义。
总之,随着Angular框架的持续更新与发展,Multi Providers作为其依赖注入系统的关键一环,将在未来更多地赋能开发者构建高性能、可扩展的Web应用。建议读者关注Angular官方文档更新以及行业技术博客,以便及时跟进相关技术和最佳实践的发展动态。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
screen - 启动多窗口终端会话,用于长时间运行任务或远程连接断开后恢复工作。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
基于Redis的分布式锁互斥性与可靠性实现及命名空间与原子性保障 04-22 可自定义刻度动画的jQuery进度条插件 02-07 jQuery和css3网站操作提示向导插件 12-28 jQuery创意响应式两栏滚动幻灯片特效 11-30 带视频播放的全屏轮播图布局特效 09-07 黑色炫酷个人摄影师网站通用模板下载 01-20 Cassandra中哈希分区与范围分区策略:数据分布、Murmur3Partitioner与负载均衡实践 11-17 [转载]java培训后好找工作吗 11-13 响应式环保包装盒设计公司网站静态模板 11-04 本次刷新还10个文章未展示,点击 更多查看。
中文建筑工程公司静态html网站模板下载 07-03 红色大气高端特色餐厅加盟网站模板 06-21 Vue.js 中的数据绑定与取消绑定:事件监听器、$destroy() 方法及 v-model 指令的运用与虚拟DOM、组件销毁的关系解析 06-20 响应式游戏应用商店单页网站html模板 06-15 自考大学通用模板下载 06-13 jqtimeline.js-简单又好用的jquery时间轴插件 06-04 [转载]Java Work 05-26 红色简洁电影售票平台网站html模板 05-02 投资集团项目展示页面网站HTML5模板 03-22 soulmate粉色干净浪漫唯美婚礼单页响应式网站模板 03-07 页面滚动时动态为元素添加class的jQuery插件 03-05
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"