此代码有效,但我需要了解它在 Angular 11 中的实际含义

This code is working but I need to understand what it actually means in Angular 11

我对第二行感到困惑。此代码有效,但我需要了解它的实际含义。

export class EmployeeService {
  employees!: EmployeeClass[];  // I think it should be *employees: EmployeeClass[] = [];*
  constructor(private http: HttpClient) {}

  getAll(): Observable < EmployeeClass[] > {
    return this.http.get('http://localhost/website/employees_ng').pipe(
      map((res: any) => {
        this.employees = res['data'];
        return this.employees;
      }),
      catchError(this.handleError));
  }

这就是 TypeScript 的明确赋值断言(!)。

来自TypeScript Docs:

Definite Assignment Assertions

The definite assignment assertion is a feature that allows a ! to be placed after instance property and variable declarations to relay to TypeScript that a variable is indeed assigned for all intents and purposes, even if TypeScript’s analyses cannot detect so.

所以它基本上是一种告诉 TypeScript 停止抱怨 employeesundefined 的方法,因为它们最终肯定会在您的代码中初始化。

这取决于你的问题指向什么。

employees!: EmployeeClass[];

感叹号告诉编译器该变量在运行时不会为空或未定义。所以没有必要从编译器方面抱怨它。

整行代码说有一个Array of EmployeeClass类型的变量employees,目前没有实例化,但会在运行时实例化。

你可以这样做

employees: EmployeeClass[] = [];

这样你总是从一个类型为Array of EmployeeClass的空数组开始,你不必再需要感叹号了,因为它已经被实例化了,编译器不会报告缺少初始化器。