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

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

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

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

其他回答

一个更好的方法是在变量的末尾加上感叹号,因为你确定它不是undefined或null,例如你正在使用一个ElementRef,需要从模板加载,不能在构造函数中定义,做如下所示的事情

class Component {
 ViewChild('idname') variable! : ElementRef;
}

只需转到tsconfig。Json和set

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

来消除编译错误。

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

你不能直接使用定赋断言吗?(参见https://www.typescriptlang.org/docs/handbook/release - notes/typescript 2 - 7. - html # definite-assignment-assertions)

即声明财产为使!:任何[];!确保typescript在运行时肯定会有一个值。

抱歉,我还没有在angular中尝试过,但当我在React中遇到完全相同的问题时,它对我来说很有用。

注释tsconfig中的//"strict": true行。json文件。

在我的Angular项目中添加Node时得到这个错误

TSError: ?无法编译TypeScript: (路径)/ base.api。ts:19:13 -错误TS2564:属性'apiRoot Path'没有初始化式,在构造函数中没有明确赋值。 private apiRootPath:字符串;

解决方案-

在tsconfig.json的compilerOptions中增加了"strictPropertyInitialization": false。

我的包。json -

"dependencies": {
    ...
    "@angular/common": "~10.1.3",
    "@types/express": "^4.17.9",
    "express": "^4.17.1",
    ...
}

参考URL - https://www.ryadel.com/en/ts2564-ts-property-has-no-initializer-typescript-error-fix-visual-studio-2017-vs2017/