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

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


当前回答

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

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

myText: string ;
}

其他回答

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

myObj: IMyObject = {} as IMyObject;

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

2021年更新:

有一个属性像"strictPropertyInitialization"

只需转到tsconfig。Json和set

“严格”:假的

来消除编译错误。

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

这个错误背后的原因是:

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

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

例子:

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

当您使用typescript@2.9.2进行升级时,它的编译器严格遵守组件类构造函数内部数组类型声明的规则。

为了解决这个问题,要么改变代码中声明的代码,要么避免编译器在“tsconfig. properties”中添加属性“strictPropertyInitialization”:false。然后再次运行NPM start。

Angular web和移动应用开发你可以访问www.jtechweb.in