议 Angular 依赖注入
一、依赖注入1. 不用依赖注入怎么写代码以学校为例,学校里有老师和学生两个群体。不使用依赖注入的写法如下: // School.ts class School { public student: Student; public teacher: Teacher; constructor () { this.student = new Student(); this.teacher = new Teacher(); } } 创建一个学校实例: // test.ts const school = new School(); // 变量 school 是一个具体的学校 在上述的例子里,老师和学生两个群体是在学校构造函数中定义的,如果现在需要修改学生类的构造函数,如增加一个参数,也就是将 上述所说的修改代码实现如下: 修改 Student 构造函数 // Student.ts class Student { stuLen: number; constructor (length: number) { this.stdLen = length; } } 修改 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. 使用依赖注入如何写使用依赖注入可以解决上述例子中强耦合的问题。 // School.ts class School { constructor (public student: Student,public teacher: Teacher) {} } 创建一个学校实例: // test.ts const student = new Student(); const teacher = new Teacher(); const school = new School(student,teacher); 可以看到,将 3. 定义依赖注入可以解除类与类之间的强耦合性,这在后期代码维护阶段带来很大的便利。如果不使用依赖注入,在后期修改了一个类,其它使用到它的地方也需要进行修改。 二、Angular 的依赖注入框架前面介绍了依赖注入的含义,我们知道确实可以解耦合,但是写法上并没有带来多少遍历,只是 依赖注入框架就是解决写法上便利的问题,按照依赖注入框架来写,我们只需要通过简单的注解,如: 具体用法可参考 Angular 依赖注入官方文档。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |