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

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


当前回答

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

其他回答

在tsconfig。json文件,在“compilerOptions”中添加:

"strictPropertyInitialization": false,

如果你想基于接口初始化一个对象,你可以用下面的语句将它初始化为空。

myObj: IMyObject = {} as IMyObject;

属性”……'没有初始化式,在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=[];
}

最佳解决方案

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

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

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

该错误是合法的,可以防止应用程序崩溃。你输入了一个数组,但它也可以是未定义的。

你有两个选项(而不是禁用typescript存在的原因…):

1. 在你的情况下,最好是输入make,尽可能未定义。

makes?: any[]
// or
makes: any[] | undefined

所以当你试图访问make时,编译器会告诉你它可能是未定义的。 否则,如果下面的// <——Not ok行在getMakes完成之前执行,或者getMakes失败,你的应用程序将崩溃,并抛出一个运行时错误。这绝对不是你想要的。

makes[0] // <-- Not ok
makes.map(...) // <-- Not ok

if (makes) makes[0] // <-- Ok
makes?.[0] // <-- Ok
(makes ?? []).map(...) // <-- Ok

2. 您可以假设它永远不会失败,并且在编写下面的代码初始化之前永远不会尝试访问它(有风险!)所以编译器不会关心它。

makes!: any[] 

更具体地说,

你的代码设计可以做得更好。定义一个局部可变变量通常不是一个好的实践。你应该在你的服务中管理数据存储:

首先是nullsafe, 其次,能够分解大量代码(包括输入,加载状态和错误) 最后避免多次无用的reftech。

下面的例子试图展示这一点,但我没有测试它,它可以改进:

type Make = any // Type it

class MakeService {

  private readonly source = new BehaviorSubject<Make[] | undefined>(undefined);
  loading = false;

  private readonly getMakes = (): Observable<Make[]> => {
    /* ... your current implementation */
  };

  readonly getMakes2 = () => {
    if (this.source.value) {
      return this.source.asObservable();
    }
    return new Observable(_ => _.next()).pipe(
      tap(_ => {
        this.loading = true;
      }),
      mergeMap(this.getMakes),
      mergeMap(data => {
        this.source.next(data);
        return data;
      }),
      tap(_ => {
        this.loading = false;
      }),
      catchError((err: any) => {
        this.loading = false;
        return throwError(err);
      }),
    );
  };
}

@Component({
  selector: 'app-vehicle-form',
  template: `
    <div *ngIf="makeService.loading">Loading...</div>
    <div *ngFor="let vehicule of vehicules | async">
      {{vehicle.name}}
    </div>
  `,
  styleUrls: ['./vehicle-form.component.css']
})
export class VehicleFormComponent implements OnInit {
  constructor(public makeService: MakeService) {}

  readonly makes = this.makeService.getMakes2().pipe(
    tap(makes => console.log('MAKES', makes))
  );

  readonly vehicules = this.makes.pipe(
    map(make => make/* some transformation */),
    tap(vehicule => console.log('VEHICLE', vehicule)),
  );

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