首页 > 解决方案 > 订阅 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未定义。任何的想法?我想在我的响应正文中发送数据。

标签: angularobservable

解决方案


地图操作员总是在订阅之前工作。它根据需要提供重写 http 响应。您使用了“map”运算符但没有返回任何内容,因此订阅数据将为空。

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

推荐阅读