简体   繁体   中英

Element implicitly has an 'any' type because expression of type '"logo"' can't be used to index type 'Object' in Angular

The problem is located on my app.component.ts , on line res['logo']

The error says:

Element implicitly has an 'any' type because expression of type '"logo"' can't be used to index type 'Object'. Property 'logo' does not exist on type 'Object'.ts(7053)

What does this error means? and why I'm having a problem.

app.component.html (part of code):

<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 (here's where the problem is showing up):

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

by default, if you do not pass a type to this.httpClient.get the response will be an Object . But TS can't be sure that logo that is a string is a valid key of Object , so it will auto convert it to type any

You should define the result type in the get :

this.http.post<{logo: string}>('arn:aws:s3:::logo-bucket', logoForm);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM