Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular TS2531:对象可能是';空';_Angular_Typescript - Fatal编程技术网

Angular TS2531:对象可能是';空';

Angular TS2531:对象可能是';空';,angular,typescript,Angular,Typescript,我有以下功能:- uploadPhoto() { var nativeElement: HTMLInputElement = this.fileInput.nativeElement; this.photoService.upload(this.vehicleId, nativeElement.files[0]) .subscribe(x => console.log(x)); } 但是,在nativeElement.files[0]上,我收到一个typ

我有以下功能:-

uploadPhoto() {
    var nativeElement: HTMLInputElement = this.fileInput.nativeElement;

    this.photoService.upload(this.vehicleId, nativeElement.files[0])
        .subscribe(x => console.log(x));
}
但是,在nativeElement.files[0]上,我收到一个typescript错误,“对象可能为“null”。有人能帮我解决这个问题吗

我试图将nativeElement声明为空值,但是没有成功


感谢您的帮助和时间。

如果您确定在所有情况下都有一个文件。 你需要确认一下

(nativeElement.files as FileList)[0]

文件
被定义为
文件列表| null
,因此它可以是
null
。您应该检查空值(如果,则使用
),如果您确定非空值,则使用非空断言运算符(

if(nativeElement.files != null) {
    this.photoService.upload(this.vehicleId, nativeElement.files[0])
        .subscribe(x => console.log(x));
}

//OR
this.photoService.upload(this.vehicleId, nativeElement.files![0])
    .subscribe(x => console.log(x));
注意
NOTNULL断言运算符不会执行任何运行时检查,它只会告诉编译器您有特殊信息,并且您知道
nativeElement.files
在运行时不会为空。如果
nativeElement.files
在运行时为空,则会错误地生成。这不是其他语言的安全导航操作员。

TypeScript 3.7于2019年11月发布。现在支持“”,这是处理可能为空的值的最简单、最安全的方法:

你只需写下:

nativeElement?.file?.name
注意问号!它们检查null/undefined,并且仅在没有任何属性(用点链接)为null/undefined时返回值

而不是

if(nativeElement!=null && nativeElement.file != null) {
  ....
}

但想象一下更复杂的情况:
crm.contract?.person?.address?.city?.latlang
,否则检查起来会更加冗长

使用Markus引用可选链接的答案,我通过将
nativeElement
强制转换为
HTMLInputElement
,然后使用
.item(0)
和可选链接操作符
访问
0th
文件来解决您的问题。

uploadPhoto() {
    var nativeElement = this.fileInput.nativeElement as HTMLInputElement

    this.photoService.upload(this.vehicleId, nativeElement?.files?.item(0))
        .subscribe(x => console.log(x));
}

是的,我更喜欢第二个concise@Johann是的,但是请注意,如果运行时
nativeElement.files
null
,您将得到一个错误<代码>
不执行运行时检查,它只是告诉编译器您知道的
nativeElement.files
永远不会为
null
,并抑制错误。是的,根据我的说明,nativeElement.files永远不应该为nulllogic@Johann好的,那对你来说应该没问题。不过,我在答案中添加了一个注释,以确保每个人都清楚这是什么
做:)完美!谢谢你,提香