议 Angular 依赖注入

前端之家收集整理的这篇文章主要介绍了议 Angular 依赖注入前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_1@依赖注入,也叫 DI,直接在学习 JAVA 的时候就遇到这个概念,无奈一直没弄明白到底是干嘛的,以及为什么要用它。最近在阅读 Angular 的官方文档时对它有的进一步的认识,总结如下。本文以 Typescript 为例的,语法和 JS 差不多,只是概念的总结,代码只是示意作用。

一、依赖注入

1. 不用依赖注入怎么写代码

@H_403_1@以学校为例,学校里有老师和学生两个群体。不使用依赖注入的写法如下:

  1. // School.ts
  2. class School {
  3. public student: Student;
  4. public teacher: Teacher;
  5. constructor () {
  6. this.student = new Student();
  7. this.teacher = new Teacher();
  8. }
  9. }
@H_403_1@创建一个学校实例:

  1. // test.ts
  2. 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 构造函数

  1. // Student.ts
  2. class Student {
  3. stuLen: number;
  4.  
  5. constructor (length: number) {
  6. this.stdLen = length;
  7. }
  8. }
@H_403_1@修改 School.ts 文件中的 Student()

  1. // School.ts
  2. class School {
  3. public student: Student;
  4. public teacher: Teacher;
  5. constructor () {
  6. this.student = new Student(60); // 这一步进行了修改,如果不传参就会报错,因为 Student 构造函数修改为有参数了
  7. this.teacher = new Teacher();
  8. }
  9. }

2. 使用依赖注入如何写

@H_403_1@使用依赖注入可以解决上述例子中强耦合的问题。

  1. // School.ts
  2. class School {
  3. constructor (public student: Student,public teacher: Teacher) {}
  4. }
@H_403_1@创建一个学校实例:

  1. // test.ts
  2. const student = new Student();
  3. const teacher = new Teacher();
  4. 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 依赖注入官方文档

猜你在找的Angularjs相关文章