在我的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严格的特性:

@ViewChild(MatSort, {static: true}) sort!: MatSort;

如果在tsonfig中禁用typescript新的严格特性。json和

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

旧的Angular指南代码工作得很好

@ViewChild(MatSort) sort: MatSort;

这里有4种方法来解决这个问题 Arunkumar Gudelli (2022) https://www.angularjswiki.com/angular/property-has-no-initializer-and-is-not-definitely-assigned-in-the-constructor/

其他回答

变量"?"旁边你可以把它。

例子:

---------> id吗?数量: ---------> 的名字吗?:字符串

在我的情况下,它与不同的声明根据新的typescript严格的特性:

@ViewChild(MatSort, {static: true}) sort!: MatSort;

如果在tsonfig中禁用typescript新的严格特性。json和

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

旧的Angular指南代码工作得很好

@ViewChild(MatSort) sort: MatSort;

这里有4种方法来解决这个问题 Arunkumar Gudelli (2022) https://www.angularjswiki.com/angular/property-has-no-initializer-and-is-not-definitely-assigned-in-the-constructor/

你可以在构造函数中这样声明属性:

export class Test {
constructor(myText:string) {
this.myText= myText;
} 

myText: string ;
}

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();
      }
     
    }

您可以为变量指定一个初始值,而不是关闭严格模式。 例如:

make: any[] = [null]; Private year: number = 0;