依赖注入是一种使程序的一部分能够访问另一部分的系统,并且可以通过配置控制其行为。

“注入”可以理解为是“new”操作符的一种替代,不再需要使用编程语言所提供的"new"操作符,依赖注入系统管理对象的生成。

依赖注入的最大好处是组件不再需要知道如何建立依赖项。它们只需要知道如何与依赖项交互。

在Angular的依赖注入系统中,不用直接导入并创建类的实例,而是使用Angular注册依赖,然后描述如何注入依赖,最后注入依赖。

依赖注入组件

为了注册一个依赖项,需要使用依赖标记(token)与之绑定。比如,注册一个API的URL,可以使用字符串API_URL作为其标记;如果是注册一个类,可以用类本身作为标记。

Angular中的依赖注入系统分为三部分:

  • 提供者(Provider)(也被作为一个绑定)映射一个标记到一系列的依赖项,其告知Angular如何创建一个对象并给予一个标记。
  • 注入器(Injector)持有一系列绑定,并负责解析依赖项,且在创建对象的时候注入它们。
  • 依赖项(Dependency)是所注入的对象。

依赖注入方式

手动方式

通过ReflectiveInjectorresolveAndCreate方法解析并创建对象,这种方式不常用。

import { Injectable } from '@angular/core';

@Injectable()
export class UserService {
user: any; setUser(newUser) {
this.user = newUser;
} getUser(): any {
return this.user;
}
}
import {
Component,
ReflectiveInjector
} from '@angular/core'; import { UserService } from '../services/user.service'; @Component({
selector: 'app-injector-demo',
templateUrl: './user-demo.component.html',
styleUrls: ['./user-demo.component.css']
})
export class UserDemoInjectorComponent {
userName: string;
userService: UserService; constructor() {
// Create an _injector_ and ask for it to resolve and create a UserService
const injector: any = ReflectiveInjector.resolveAndCreate([UserService]); // use the injector to **get the instance** of the UserService
this.userService = injector.get(UserService);
} signIn(): void {
// when we sign in, set the user
// this mimics filling out a login form
this.userService.setUser({
name: 'Nate Murray'
}); // now **read** the user name from the service
this.userName = this.userService.getUser().name;
console.log('User name is: ', this.userName);
}
}

* 注意UserService类上的@Injectable()装饰器,这说明了这个类是可以作为注入对象的。

NgModule方式

使用NgModule注册将要用到的依赖项(在providers中),并用装饰器(一般是构造器)指定哪些是正在使用的。

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common'; // imported here
import { UserService } from '../services/user.service'; @NgModule({
imports: [
CommonModule
],
providers: [
UserService // <-- added right here
],
declarations: []
})
export class UserDemoModule { }
import { Component, OnInit } from '@angular/core';

import { UserService } from '../services/user.service';

@Component({
selector: 'app-user-demo',
templateUrl: './user-demo.component.html',
styleUrls: ['./user-demo.component.css']
})
export class UserDemoComponent {
userName: string;
// removed `userService` because of constructor shorthand below // Angular will inject the singleton instance of `UserService` here.
// We set it as a property with `private`.
constructor(private userService: UserService) {
// empty because we don't have to do anything else!
} // below is the same...
signIn(): void {
// when we sign in, set the user
// this mimics filling out a login form
this.userService.setUser({
name: 'Nate Murray'
}); // now **read** the user name from the service
this.userName = this.userService.getUser().name;
console.log('User name is: ', this.userName);
}
}

Providers

类标记

providers: [ UserService ]是以下方式的的简写:

providers: [
{ provide: UserService, useClass: UserService }
]

provide是标记,useClass是所依赖的对象。两者为映射关系。

值标记

providers: [
{ provide: 'API_URL', useValue: 'http://my.api.com/v1' }
]

使用时需要加上@Inject:

import { Inject } from '@angular/core';

export class AnalyticsDemoComponent {
constructor(@Inject('API_URL') apiUrl: string) {
// works! do something w/ apiUrl
}
}

工厂方式

绑定依赖项时还可以通过工厂方式实现更复杂的绑定逻辑,并且这种方式下可以传入必要参数以创建所需的对象。

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {
Metric,
AnalyticsImplementation
} from './analytics-demo.interface';
import { AnalyticsService } from '../services/analytics.service'; // added this ->
import {
HttpModule,
Http
} from '@angular/http'; @NgModule({
imports: [
CommonModule,
HttpModule, // <-- added
],
providers: [
// add our API_URL provider
{ provide: 'API_URL', useValue: 'http://devserver.com' },
{
provide: AnalyticsService, // add our `deps` to specify the factory depencies
deps: [ Http, 'API_URL' ], // notice we've added arguments here
// the order matches the deps order
useFactory(http: Http, apiUrl: string) { // create an implementation that will log the event
const loggingImplementation: AnalyticsImplementation = {
recordEvent: (metric: Metric): void => {
console.log('The metric is:', metric);
console.log('Sending to: ', apiUrl);
// ... You'd send the metric using http here ...
}
}; // create our new `AnalyticsService` with the implementation
return new AnalyticsService(loggingImplementation);
}
},
],
declarations: [ ]
})
export class AnalyticsDemoModule { }

ng-book札记——依赖注入的更多相关文章

  1. ng 依赖注入

    将依赖的对象注入到当前对象,直接去使用依赖的对象即可. 降低耦合度.提高开发速度.. 文件压缩:yui-compressor有两种方案:①CLI(command line interface)java ...

  2. ng依赖注入

    依赖注入 1.注入器在组件的构造函数中写服务constructor(private httpreq:HttpService) { } 2.提供器 providers: [HttpService],

  3. angular路由 模块 依赖注入

    1.模块 var helloModule=angular.module('helloAngular',[]); helloModule.controller('helloNgCrtl',['$scop ...

  4. AngularJS学习笔记之依赖注入

    最近在看AngularJS权威指南,由于各种各样的原因(主要是因为我没有money,好讨厌的有木有......),于是我选择了网上下载电子版的(因为它不要钱,哈哈...),字体也蛮清晰的,总体效果还不 ...

  5. 4.了解AngularJS模块和依赖注入

    1.模块和依赖注入概述 1.了解模块 AngularJS模块是一种容器,把代码隔离并组织成简洁,整齐,可复用的块. 模块本身不提供直接的功能:包含其他提供功能的对象的实例:控制器,过滤器,服务,动画 ...

  6. AngularJS——依赖注入

    依赖注入    依赖注入(DI)是一个经典的设计模式, 主要是用来处理组件如何获得依赖的问题.关于DI,推荐阅读Martin Flower的文章(http://martinfowler.com/art ...

  7. AngularJS学习--- AngularJS中XHR(AJAX)和依赖注入(DI) step5

    前言:本文接前一篇文章,主要介绍什么是XHR,AJAX,DI,angularjs中如何使用XHR和DI. 1.切换工具目录 git checkout -f step- #切换分支 npm start ...

  8. angular2 学习笔记 ( DI 依赖注入 )

    refer : http://blog.thoughtram.io/angular/2016/09/15/angular-2-final-is-out.html ( search Dependency ...

  9. (五)Angularjs - 依赖注入

    如何找到API? AngularJS提供了一些功能的封装,但是当你试图通过全局对象angular去 访问这些功能时,却发现与以往遇到的库大不相同. 比如,AngularJS暴露了一个全局对象:angu ...

随机推荐

  1. jenkins创建pipeline

    新建任务的时候,有两个流水线相关的任务类型,如下图.其中:流水线更加针对单主干模式的开发,在主干目录下放一个Jenkinsfile文件,其中该文件保存了从SCM拉代码.构建.测试.发布等等流程. 而M ...

  2. servlet filter中使用autowired无法注入

    问题: 我们为了避免未经授权的人直接通过url访问我们的页面,配置了如下filter <!-- 登录过滤器 --> <filter> <filter-name>se ...

  3. GET和POST两种基本请求方法的区别

    文章来源:http://www.cnblogs.com/logsharing/p/8448446.html GET和POST是HTTP请求的两种基本方法,要说它们的区别,接触过WEB开发的人都能说出一 ...

  4. WPF在在设计模式,使用动态样式

    1.问题分析 WPF有时候要用到主题样式,比如颜色主题(红色.黄色之类的)通常是key相同,而value不同,比如会这么写: Background="{DynamicResource Bac ...

  5. MongDB配置方法

    先下载安装包 安装 方法一:命令行启动 在 C:\MongoDB\Server\3.4目录下建立data文件夹, data里面建立db文件夹 bin目录下运行 mongod --dbpath C:\M ...

  6. CodeForces 916E Jamie and Tree(树链剖分+LCA)

    To your surprise, Jamie is the final boss! Ehehehe. Jamie has given you a tree with n vertices, numb ...

  7. [LeetCode] Maximum Average Subarray I 子数组的最大平均值

    Given an array consisting of n integers, find the contiguous subarray of given length k that has the ...

  8. [LeetCode] K-diff Pairs in an Array 数组中差为K的数对

    Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in t ...

  9. [LeetCode] Max Consecutive Ones II 最大连续1的个数之二

    Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at mos ...

  10. PyQt5 QSerialPort子线程操作

    环境: python3.6 pyqt5 只是简单的一个思路,请忽略脆弱的异常防护: # -*- coding: utf-8 -*- import sys from PyQt5.QtWidgets im ...