Search code examples
angular6angular-httpclient

Why is my Angular 6 httpClient POST request firing twice


I am uploading images from my Angular front end to C# web api back end, and the POST request in the service is calling twice, although the service is only called once.

Debugged through and the service is only called once, but seeing 2 post requests in Fiddler, and the network tab in Dev tools of browser

HTML:

<form [formGroup]="uploadForm" (ngSubmit)="upload()" >
  <input id="cin" name="cin" type="file" (change)="fileChangeEvent($event)" 
    placeholder="Upload a file..." multiple />

  <button type="submit" class="btn btn-success btn-s">
    <i class="glyphicon glyphicon-open-file"></i>&nbsp;Upload
  </button>
</form>

Component:

export class UploadCreateComponent implements OnInit {
  public uploadForm: FormGroup;
  public successMessage: string;
  public errorMessage: string;
  selectedFile: File;
  files: Array<File> = [];

  constructor(fb: FormBuilder, private service: UploadService, private cd: ChangeDetectorRef) {
    this.uploadForm = fb.group({
      files: [null, Validators.required]
    });
  }

  ngOnInit() {
  }

  upload() {
    const files: Array<File> = this.files;
    if (files.length === 0) {
      this.errorMessage = 'Please select some files';
      return;
    }
    this.service.createUpload(files).subscribe(event => {
      console.log(event);
      this.successMessage = 'Success';
    }, (error) => {
      console.error(error);
      this.errorMessage = 'Error: ' + error;
    });
  }

  fileChangeEvent(fileInput: any) {
    this.files = <Array<File>>fileInput.target.files;
  }
}

Service:

public createUpload(files: any): Observable<any> {
    let input = new FormData();
    for (let i = 0; i < files.length; i++) {
      input.append('files', files[i]);
    }
    return this.http.post(this.baseUrl + 'api/Upload/PostImage', input);
  }

Solution

  • I found the issue....my back end was returning an error: "Unexpected token f in JSON at position 2" I was trying to do the following in my C# web api controller:

        [HttpPost, Route("PostImage"), DisableRequestSizeLimit]
        public async Task<IActionResult> PostImage(List<IFormFile> files)
        {
            if (files == null || files.Count == 0)
            {
                return BadRequest("Invalid files");
            }
    
            var imageUploadCount = await _context.UploadFile(files);
            if(imageUploadCount > 0)
            {
                var resultMessage = string.Format($"{imageUploadCount} file(s) uploaded successfully.");
                return Ok(resultMessage);
            }
            return BadRequest("No files uploaded");
    
        }
    

    If I remove the result message, it all works. Not sure why its erroring on this, but thats a different question.