简体   繁体   中英

How to fix error when trying to upload file to backend?

I'am trying to upload a file to the server by using a service which passes the file to the php backend. It works, but only once. If I try to repeat uploading another file (without reloading the page) it does not get send and this error occurs: ERROR TypeError: "this.fileManagerService.uploadFile is not a function"

playground.component.html

<form [formGroup]="form" (ngSubmit)="onSubmit()">
    <input type="file" name="avatar" (change)="onFileSelect($event)" />
    <button type="submit">Upload</button>
</form>

playground.component.ts

export class PlaygroundComponent implements OnInit {

  form: FormGroup;
  fileManagerResponse;

  constructor(private formBuilder: FormBuilder, private fileManagerService: FileManagerService) { }

  ngOnInit() {
    this.form = this.formBuilder.group({
      avatar: ['']
    });
  }

  onFileSelect(event) {
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.form.get('avatar').setValue(file);
    }
  }

  onSubmit() {
    const formData = new FormData();
    formData.append('avatar', this.form.get('avatar').value);

    this.fileManagerService.uploadFile(formData).subscribe(
      (res) => {
        this.fileManagerService = res;
          console.log(res);
      },
      (err) => {  
        console.log(err);
      }
    );
  }

}

FileManagerService.ts

export class FileManagerService {

  SERVER_URL: string = "http://127.0.0.1/backend/api/";

  constructor(private httpClient: HttpClient) { }

  public uploadFile(data) {
    let uploadURL = `${this.SERVER_URL}/filemanager/upload.php`;
    return this.httpClient.post<any>(uploadURL, data);
  }
}

The error occurred in below line.

this.fileManagerService = res;

You cannot assign res to the instance of the FileManagerService . Remove it. Everything will be fine.

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