簡體   English   中英

訂閱可觀察角度未定義

[英]Subscribing on angular observable is undefined

我對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()這一行都uploadSingleFile()

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

變量image未定義。 任何想法? 我想在這里將數據發送到我的響應正文中。

地圖操作員始終在訂閱之前工作。 它提供所需的重寫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.
        })
      );
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM