![](/img/trans.png)
[英]Element implicitly has an 'any' type because expression of type 'string' can't be used to index type in Angular
[英]Element implicitly has an 'any' type because expression of type '"logo"' can't be used to index type 'Object' in Angular
问题出在我的app.component.ts上,在线res['logo']
错误说:
元素隐式具有 'any' 类型,因为类型 '"logo"' 的表达式不能用于索引类型 'Object'。 类型“Object”.ts(7053) 上不存在属性“logo”
这个错误是什么意思? 以及为什么我遇到问题。
app.component.html (部分代码):
<form [formGroup]="profileForm" (ngSubmit)="submitProfile()">
<input (change)="onLogoSelect($event)" placeholder="Upload Company Logo" type="file" formControlName="companyLogo">
<button (click)="onLogoUpload()">Upload Company Logo</button>
<div *ngIf="logoUrl">
Preview Image from AWS
<br>
<img src="https://logo-bucket.s3.amazonaws.com/{{ logoUrl }}" alt=""> <br>
</div>
</form>
app.component.ts (这里是问题出现的地方):
import { LogoUploadService } from 'app/logo/logo-upload.service';
export class EmployerAccountComponent implements OnInit {
logoObj: File;
logoUrl: string;
constructor(
private logoUploadService: LogoUploadService,
){
... (just some codes here)
}
onLogoSelect(event: Event): void {
const FILE = (event.target as HTMLInputElement).files[0];
this.logoObj = FILE;
}
onLogoUpload() {
const logoForm = new FormData();
logoForm.append('logo', this.imageObj);
this.logoUploadService.imageUpload(logoForm).subscribe(res => {
this.logoUrl = res['logo']; // <--------------here's the problem 'res['logo']'
});
}
}
logo-upload.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class LogoUploadService {
constructor(private http: HttpClient) { }
// API call
logoUpload(logoForm: FormData){
console.log('logo uploading');
return this.http.post('arn:aws:s3:::logo-bucket', logoForm);
}
}
默认情况下,如果您不向this.httpClient.get
传递类型,则响应将是一个Object
。 但是 TS 不能确定作为string
logo
是Object
的有效键,因此它会自动将其转换为输入any
您应该在 get 中定义结果类型:
this.http.post<{logo: string}>('arn:aws:s3:::logo-bucket', logoForm);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.