问题位于我的app.component.ts,在线res['logo']
错误提示:
Element隐式地有一个'any'类型,因为'"logo"'类型的表达式不能用于索引类型'Object'。属性'logo'在类型'Object'上不存在。ts(7053)
这个错误是什么意思?和为什么我有问题。
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);