在我的Angular应用中,我有一个组件:

import { MakeService } from './../../services/make.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-vehicle-form',
  templateUrl: './vehicle-form.component.html',
  styleUrls: ['./vehicle-form.component.css']
})
export class VehicleFormComponent implements OnInit {
  makes: any[];
  vehicle = {};

  constructor(private makeService: MakeService) { }

  ngOnInit() {
    this.makeService.getMakes().subscribe(makes => { this.makes = makes
      console.log("MAKES", this.makes);
    });
  }

  onMakeChange(){
    console.log("VEHICLE", this.vehicle);
  }
}

但是在“制造”属性中我犯了一个错误。 我不知道该怎么办……


当前回答

你需要禁用——strictPropertyInitialization Sajeetharan提到的,或者做这样的事情来满足初始化需求:

makes: any[] = [];

其他回答

在tsconfig中添加一些配置时,我们可能会得到这样的消息:Property没有初始化式,并且在构造函数中没有明确地赋值。json文件,以便在严格模式下编译Angular项目:

"compilerOptions": {
  "strict": true,
  "noImplicitAny": true,
  "noImplicitThis": true,
  "alwaysStrict": true,
  "strictNullChecks": true,
  "strictFunctionTypes": true,
  "strictPropertyInitialization": true,

实际上,在使用成员变量之前,编译器会报错成员变量没有定义。

对于一个在编译时没有定义的成员变量的例子,一个成员变量有一个@Input指令:

@Input() userId: string;

我们可以通过声明变量可以是可选的来关闭编译器:

@Input() userId?: string;

但是,我们将不得不处理变量未定义的情况,并使用一些这样的语句使源代码混乱:

if (this.userId) {
} else {
}

相反,知道这个成员变量的值将及时定义,也就是说,它将在使用之前定义,我们可以告诉编译器不要担心它没有被定义。

告诉编译器这一点的方法是添加!明确赋值断言运算符,如:

@Input() userId!: string;

现在,编译器知道这个变量虽然没有在编译时定义,但应该在运行时以及在使用它之前及时定义。

现在由应用程序来确保在使用该变量之前已经定义了该变量。

作为一种额外的保护,我们可以在使用变量之前断言变量正在被定义。

我们可以断言变量已经定义,也就是说,所需的输入绑定实际上是由调用上下文提供的:

private assertInputsProvided(): void {
  if (!this.userId) {
    throw (new Error("The required input [userId] was not provided"));
  }
}

public ngOnInit(): void {
  // Ensure the input bindings are actually provided at run-time
  this.assertInputsProvided();
}

知道了变量的定义,现在可以使用变量:

ngOnChanges() {
  this.userService.get(this.userId)
    .subscribe(user => {
      this.update(user.confirmedEmail);
    });
}

注意,ngOnInit方法是在输入绑定尝试之后调用的,即使没有向绑定提供实际的输入。

而ngOnChanges方法在尝试输入绑定之后才会被调用,并且仅当有实际输入提供给绑定时才会调用。

新版本的typescript引入了严格的类初始化,这意味着你需要在构造函数体中初始化类中的所有属性,或者通过属性初始化器。在typescript文档中检查它 为了避免这种情况,您可以添加(!或者?

make!: any[] or make? : any[] 

否则,如果您希望在项目中永久删除严格类检查 你可以在tsconfig中设置strictPropertyInitialization": false。json文件

" compilerOptions ": { .... “noImplicitReturns”:假的, .... “strictPropertyInitialization”:假的 },

你也可以添加@ts-ignore来使编译器只在这种情况下静音:

//@ts-ignore
makes: any[];

直接进入tsconfig。Ts和add "strictPropertyInitialization": false,进入compilerOptions对象。

如果还没有解决,请重新打开代码编辑器。

例子:

"compilerOptions" : {
  "strictPropertyInitialization": false,
}

make变量后加一个问号。

  makes?: any[];
  vehicle = {};

  constructor(private makeService: MakeService) { }

现在应该可以工作了。 我使用的是angular 12,它可以在我的代码中工作。