前端之家收集整理的这篇文章主要介绍了
议 Angular 依赖注入,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_1@依赖注入,也叫 DI,直接在学习 JAVA 的时候就遇到这个概念,无奈一直没弄明白到底是干嘛的,以及为什么要用它。最近在阅读 Angular 的官方文档时对它有的进一步的认识,总结如下。本文以 Typescript 为例的,语法和 JS 差不多,只是概念的总结,代码只是示意作用。
一、依赖注入
1. 不用依赖注入怎么写代码
@H_
403_1@以学校为例,学校里有老师和学生两个群体。不使用依赖注入的写法如下:
- // School.ts
- class School {
-
- public student: Student;
- public teacher: Teacher;
-
- constructor () {
- this.student = new Student();
- this.teacher = new Teacher();
- }
- }
@H_
403_1@创建一个学校实例:
- // test.ts
- const school = new School(); // 变量 school 是一个具体的学校
@H_
403_1@在上述的例子里,老师和学生两个群体是在学校构造
函数中定义的,如果现在需要
修改学生类的构造
函数,如
增加一个参数,也就是将
new Student()@H_403_18@ 改为 new Student(lenth)@H_403_18@ 那么还需要到 School.ts@H_403_18@ 中去修改代码。这一点无疑跟我们的解耦性设计思路违背。我们希望的是各个类尽量做到不想关,改一个地方,不需要去改其它地方。
@H_403_1@上述所说的修改代码实现如下:
@H_403_1@修改 Student 构造函数
- // Student.ts
- class Student {
- stuLen: number;
-
- constructor (length: number) {
- this.stdLen = length;
- }
- }
@H_403_1@修改 School.ts 文件中的 Student()
- // School.ts
- class School {
-
- public student: Student;
- public teacher: Teacher;
-
- constructor () {
- this.student = new Student(60); // 这一步进行了修改,如果不传参就会报错,因为 Student 构造函数被修改为有参数了
- this.teacher = new Teacher();
- }
- }
2. 使用依赖注入如何写
@H_403_1@使用依赖注入可以解决上述例子中强耦合的问题。
- // School.ts
- class School {
-
- constructor (public student: Student,public teacher: Teacher) {}
-
- }
@H_403_1@创建一个学校实例:
- // test.ts
- const student = new Student();
- const teacher = new Teacher();
- const school = new School(student,teacher);
@H_403_1@可以看到,将 student@H_403_18@ 和 teacher@H_403_18@ 在 test.ts@H_403_18@ 中先进行实例化,再将实例化对象以传参的形式传递给 School 构造函数,在 School 类的 construtor 函数中以参数的形式进行接收。这样一来,不管 Student 类有什么改变,School.ts 都不许需要进行任何修改。这就是依赖注入的含义。
3. 定义
@H_403_1@依赖注入可以解除类与类之间的强耦合性,这在后期代码维护阶段带来很大的便利。如果不使用依赖注入,在后期修改了一个类,其它使用到它的地方也需要进行修改。
二、Angular 的依赖注入框架
@H_403_1@前面介绍了依赖注入的含义,我们知道确实可以解耦合,但是写法上并没有带来多少遍历,只是 new@H_403_18@ 操作的位置改变了而已。
@H_403_1@依赖注入框架就是解决写法上便利的问题,按照依赖注入框架来写,我们只需要通过简单的注解,如:@Injectable@H_403_18@ 就可以创建构造函数实例,不需要再用 new 了。
@H_403_1@具体用法可参考 Angular 依赖注入官方文档。