Angular 12+依赖注入教程

150 阅读5分钟

Angular 12+依赖注入教程

依赖性注入,简而言之,是指引用其他类的类。它是一种设计模式,允许单个类从其他来源请求依赖性。

在本教程中,我们将构建一个使用依赖注入的学生名单Angular 12应用样本。

教程要求

  • 在你的本地开发环境中安装Angular CLI(首选最新版本)。
  • 有Angular的基本知识。
  • 有JavaScript或TypeScript方面的知识。

预期结果

本教程旨在让你开始学习Angular 12依赖注入。通过学习本教程,你将对DI有一个深入的了解,在实施自己的项目时,你可能会有所进步。

开始学习Angular依赖注入

依赖注入是关于资源共享的。

比方说,你有一个StudentServiceStudentComponent ,显示一个学校的学生列表。我们可以说组件类依赖于服务类来显示数据,因为我们正在使用服务从API获取数据,我们将在下一节看到。

因此,必须牢记,依赖注入是一种编程方法的风格,它使你作为开发者能够写出相互沟通的代码。

因此,例如,当一个类没有给定的资源时,它可以快速地从另一个拥有该资源的类型中获得该资源,如此反复。

创建Angular服务

现在我们已经有了DI的背景知识,让我们创建一个服务,用来返回某个公司的实习生名单。

服务是一个在编程中广泛使用的术语,特别是在微服务的世界中。它只是一个函数或一组方法,用来处理一个特定的任务。

让我们首先创建一个学生模型,如下图所示。

cd injectionExample
ng g i student

输出。

CREATE src/app/student.ts (29 bytes)

接下来,复制并添加以下内容到这个模型中,如下图所示。

export interface Student {
  studentFirstName: string;
  studentLastName: string;
  studentRegistrationNumber: string;
  studentCourse: string;
  studentYearOfStudy: number;
  reportingDate: string;
  college: string;
}

现在我们有了这个模型,让我们继续创建一个服务,它将包含显示学生名单的功能。

需要注意的是,我们创建这些服务的原因是为了松散地耦合我们的应用程序,并允许重复使用。

运行下面的命令来创建studentListService

 ng g service student-list

输出。

CREATE src/app/student-list.service.spec.ts (359 bytes)
CREATE src/app/student-list.service.ts (140 bytes)

现在我们有了一个服务,让我们添加一个函数来返回实习生的列表和他们各自的细节。

import { Injectable } from '@angular/core';
import {Student} from './student';

@Injectable({
  providedIn: 'root'
})
export class StudentListService {

  getInternsDetails(): Student[] {
    return [
      {
        studentFirstName: 'John',
        studentLastName: 'Doe',
        studentRegistrationNumber: 'TRD12345STR',
        studentCourse: 'Computer Science',
        studentYearOfStudy: 1,
        reportingDate: '2019-07-20',
        college: 'University of Test1',
      },
      {
        studentFirstName: 'Alice',
        studentLastName: 'Liz',
        studentRegistrationNumber: 'DRTRD12345STR',
        studentCourse: 'Software Engineering',
        studentYearOfStudy: 1,
        reportingDate: '2020-07-19',
        college: 'University of Test2',
      },
      {
        studentFirstName: 'Bob',
        studentLastName: 'Miro',
        studentRegistrationNumber: 'YR6353',
        studentCourse: 'Information technology',
        studentYearOfStudy: 1,
        reportingDate: '2019-07-20',
        college: 'University of Test3',
      },
      {
        studentFirstName: 'Jakob',
        studentLastName: 'Jack',
        studentRegistrationNumber: 'YTT64749EJFHR',
        studentCourse: 'Computer Engineering',
        studentYearOfStudy: 1,
        reportingDate: '2019-02-10',
        college: 'University of Test7',
      },
      {
        studentFirstName: 'Prince',
        studentLastName: 'Sawoo',
        studentRegistrationNumber: 'ETRHDDIE857EHD',
        studentCourse: 'Computer Science',
        studentYearOfStudy: 1,
        reportingDate: '2019-03-30',
        college: 'University of Test10',
      }
    ];
  }
}

让我们分析一下上述服务。

  • 第1行- 我们正在导入injectable 装饰器。没有这个装饰器,这个服务不能被其他应用程序组件注入(请求)。
  • 第2行--Student 模型是从./student 中导入的。通常的做法是将所有的服务都放在service 目录中。请随意测试一下。
  • 第5行-我们有一个StudentListService 类。在这个类里面,我们定义了getInternsDetails() 方法,该方法返回一个数组的Student 信息。

如何在一个组件中注入服务

现在我们已经有了一个可以使用的服务,让我们继续,通过执行以下命令创建一个学生组件。

ng g c student

输出。

CREATE src/app/student/student.component.css (0 bytes)
CREATE src/app/student/student.component.html (26 bytes)
CREATE src/app/student/student.component.spec.ts (635 bytes)
CREATE src/app/student/student.component.ts (273 bytes)
UPDATE src/app/app.module.ts (400 bytes)

编辑src/app/student/student.component.ts ,如下图所示。

import { Component, OnInit } from '@angular/core';
import {StudentListService} from '../student-list.service';
import {Student} from '../student';

@Component({
  selector: 'app-student',
  templateUrl: './student.component.html',
  styleUrls: ['./student.component.css']
})
export class StudentComponent implements OnInit {

// local array tohold the list of students
  students: Student[];
  // we're injecting the studentListService (this is Dependency injection in action)
  constructor(private studentListService: StudentListService) { }

  ngOnInit() {
    this.getStudentsList();
  }
  //getting the list of students and assigning the list to students array
  getStudentsList() {
    this.students = this.studentListService.getInternsDetails();
  }
}

在上面的组件类中,我们已经定义了students 数组,我们将用它来保存学生的列表。

然后我们注入之前创建的StudentListService 。这就是Angular中实现依赖注入的方式。

我们还创建了getStudentsList() 方法,用来从服务中获取学生的详细信息。我们将结果分配给我们在本地创建的学生数组。我们在ngOnInit() 方法中调用这个方法,在页面加载时获得学生的详细信息。

显示服务中的数据

现在我们已经使用了我们的服务,让我们继续在浏览器上显示这些数据。

编辑src/app/student/student.component.html ,如下图所示。

<div>
<table class="table table-stripped table-active">
  <thead class="thead-light">
  <th>#</th>
  <th>First Name</th>
  <th>Last Name</th>
  <th>Admission Number</th>
  <th>Course</th>
  <th>Year Of Study</th>
  <th>Reported On</th>
  <th>College</th>
  </thead>
  <tbody>
  <tr *ngFor="let student of students;let i=index">
    <td>{{i+1}}</td>
    <td>{{student.studentFirstName}}</td>
    <td>{{student.studentLastName}}</td>
    <td>{{student.studentRegistrationNumber}}</td>
    <td>{{student.studentCourse}}</td>
    <td>{{student.studentYearOfStudy}}</td>
    <td>{{student.reportingDate}}</td>
    <td>{{student.college}}</td>
  </tr>
  </tbody>
</table>
</div>

现在在你的应用程序的根部执行以下命令来运行你的Angular应用程序。

ng serve --port 4200

预期的输出。

Student table

结论

在本教程中,我们已经用例子讨论了Angular DI的一系列概念。我们看到了服务是如何被创建,然后在一个组件中被消费的。我们还进一步在浏览器上测试了我们的应用程序。