在我的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);
  }
}

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


当前回答

这是因为typescript 2.7.2包含了严格的类检查,其中所有属性都应该在构造函数中声明。所以要解决这个问题,只需添加一个感叹号(!),比如:

name!:string;

其他回答

遵循2个步骤来解决这个问题:

"strictPropertyInitialization": tsconfig.json中的错误条目 ctrl+c在终端上停止你的服务器(检查终端,它在哪里运行),然后用你使用的命令再次运行它,比如ng serve 这2个步骤,应该可以解决你的问题。因为它解决了我的问题。欢呼声……;)

2021年更新:

有一个属性像"strictPropertyInitialization"

只需转到tsconfig。Json和set

“严格”:假的

来消除编译错误。

否则你需要初始化所有的变量这有点烦人。

这个错误背后的原因是:

typescript是一种比javascript更安全的语言。 尽管这种安全性是通过启用严格特性来增强的。所以每次当你初始化一个变量时,typescript都希望它们赋一个值。

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

//@ts-ignore
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方法在尝试输入绑定之后才会被调用,并且仅当有实际输入提供给绑定时才会调用。

改变

fieldname?: any[]; 

:

fieldname?: any;