为什么我的Angular 6 httpClient POST请求触发两次

时间:2019-01-10 16:05:57

标签: angular6 angular-httpclient

我将图像从Angular前端上传到C#Web api后端,并且服务中的POST请求被调用两次,尽管该服务仅被调用一次。

经过调试,该服务仅被调用一次,但是在Fiddler中看到2个发布请求,并且在浏览器的Dev工具中看到了“网络”标签

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>

组件:

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

服务:

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

1 个答案:

答案 0 :(得分:0)

我发现了问题。...我的后端返回错误: “ JSON中位置2处的意外令牌f” 我试图在C#Web API控制器中执行以下操作:

    [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");

    }

如果我删除结果消息,则一切正常。 不知道为什么会因此而出错,但这就是一个不同的问题。