Matthias Burger
Matthias Burger

Reputation: 5946

Subscribing on angular observable is undefined

I'm pretty new to angular and now trying to upload a file and when the file is uploaded successfully it shall create an entry in database with the data that is returned by the api.

for the upload i'm using

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

This is my function for uploading:

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

the fileService looks like:

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

the api function that is called:

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

It works until this line in uploadSingleFile()

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

the variable image is undefined. any idea? I'd like to have here the data sent in my response body.

Upvotes: 1

Views: 199

Answers (1)

nevzatopcu
nevzatopcu

Reputation: 1085

Map operator always work before subscribe. It provide rewrite http response as you want. You used "map" operator but did not return anything, so subscribe data is going to be empty.

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

Upvotes: 2

Related Questions