订阅可观察的角度未定义

时间:2019-07-25 11:58:01

标签: angular observable

我对angular还是很陌生,现在尝试上传文件,当文件成功上传后,它将使用api返回的数据在数据库中创建一个条目。

我正在使用的上传

import { FileUploader } from 'ng2-file-upload';

这是我的上传功能:

uploadSingleFile() {
  if (this.uploader.queue.length <= 0)
    return;

  const file = this.uploader.queue[0];
  const fileItem = file._file;
  const data = new FormData();
  data.append('file', fileItem);

  this.uploadFile(data, () => file.remove()).subscribe((image: any) => {
    this.uploadedFile = image;
  });
}

uploadFile(data: FormData, onSuccess: any): Observable<any> {
  return this.fileService.upload(data, onSuccess, r => { console.error(r); });
}

fileService如下:

upload(model: any, onSuccess: any = undefined, onError: any = undefined) {
    return this.httpClient
      .post(`${this.baseUrl}upload`, model, { observe: 'response' })
      .pipe(
        map((response: any) => {

          console.log(response.status); 
          if (response.status === 201) { // this works, I'm getting Status 201
            if (onSuccess !== undefined)
              onSuccess(response);
          }
          else if (onError !== undefined)
            onError(response);
        })
      );
  }

被称为的api函数:

[HttpPost, Route("upload")]
public async Task<ActionResult> Upload()
{
    // ...

    FileForUploadResponseDto fileForUploadDto = new FileForUploadResponseDto
    {
        FilePath = fileName,
        CreationDate = DateTime.Now,
        Title = file.FileName,
        Size = fileLength
    };


    return StatusCode(201, fileForUploadDto);
}

它一直有效,直到uploadSingleFile()

中的这一行
this.uploadFile(data, () => file.remove()).subscribe((image: any) => {
  this.uploadedFile = image;
});
  

变量image未定义。任何想法?我想在这里将数据发送到我的响应正文中。

1 个答案:

答案 0 :(得分:2)

地图操作员始终在订阅之前工作。它提供所需的重写HTTP响应。您使用了“地图”运算符,但未返回任何内容,因此订阅数据将为空。

upload(model: any, onSuccess: any = undefined, onError: any = undefined) {
    return this.httpClient
      .post(`${this.baseUrl}upload`, model, { observe: 'response' })
      .pipe(
        map((response: any) => {

          console.log(response.status); 
          if (response.status === 201) { // this works, I'm getting Status 201
            if (onSuccess !== undefined)
              onSuccess(response);
          }
          else if (onError !== undefined)
            onError(response);
            return response.body; --> you should add this line.
        })
      );
  }