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

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


当前回答

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

其他回答

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

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

1)你可以像下面的代码一样应用它。当你这样做的时候,系统不会给出一个错误。

“明确赋值断言”(!)来告诉TypeScript我们知道这个值

详细信息

@Injectable()
export class Contact {
  public name !:string;
  public address!: Address;
  public digital!: Digital[];
  public phone!: Phone[];
}

2)第二种方法是在这里创建一个构造函数并定义值。

export class Contact {
  public name :string;
  public address: Address;
  public digital: Digital[];
  public phone: Phone[];

  constructor( _name :string,
     _address: Address,
     _digital: Digital[],
     _phone: Phone[])
  {
    this.name=_name;
    this.address=_address;
    this.digital=_digital;
    this.phone=_phone;
  }
}

3)第三种选择是创建一个get属性并按如下方式赋值

  export class Contact {
      public name :string="";
      public address: Address=this._address;
    
      get _address(): Address {
        return new Address();
      }
     
    }

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

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

属性”……'没有初始化式,在Angular的构造函数错误修复中也没有明确赋值

解决方法1:关闭strictPropertyInitialization标志

在Angular应用中修复这个错误的简单方法是在tsconfig中的typescript编译器选项中禁用——strictPropertyInitialization标志。json文件。

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

解决方案2:向属性添加未定义的类型

有一个未定义的属性是可以的。

因此,在声明变量时,将未定义的类型添加到属性。

employees: Employee[];

//Change to 

employees : Employee[] | undefined;

解决方案3:向属性添加明确的赋值断言

如果你知道,我们将在以后的时间点分配财产。

最好在属性中添加明确的赋值断言。也就是说,员工。

employees!: Employee[];

解决方案4:向属性添加初始化式

消除此类型错误的另一种方法是向属性添加显式初始化式。

employees: Employee[] = [];

解决方案5:在构造函数中赋值

否则,可以在构造函数中为属性赋值。

employees: Employee[];

constructor() { 
    this.employees=[];
}

最佳解决方案

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