Search code examples
angularangular5toastr

ngx-toastr not working inside upload function of Angular 5 service


I am using ngx-toastr in my Angular 5 project. I have a service in my project which is being used to upload the files to a AWS bucket.

The Problem is I want to use Ngx-toastr inside my service to notify if the file was uploaded successfully or there was some error, but it's not working. Can anyone please help me?

Here is my upload_file_service:

import { Injectable } from '@angular/core';
import * as AWS from 'aws-sdk/global';
import * as S3 from 'aws-sdk/clients/s3';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
@Injectable()
export class UploadFileService {

  FOLDER = 'sample';

  constructor(
    private spinner: NgxSpinnerService,
    private _toastr: ToastrService,
  ) { }

  uploadfile(file) {
    this._toastr.info("uploading" , "Info");  //this one is working fine.
    // this.spinner.show();
    const bucket = new S3(
      {
        accessKeyId: 'sample',
        secretAccessKey: 'sample',
        region: 'sample'
      }
    );

    const params = {
      Bucket: 'bucek_name',
      Key: this.FOLDER + file.name,
      Body: file
    };

    bucket.upload(params, function (err, data) {
      if (err) {
        console.log('There was an error uploading your file: ', err);
        // this.spinner.hide();
        // this._toastr.error("File Upload Failed, Please Try Again!",  "Error");
        return false;
      }
      console.log('Successfully uploaded file.', data.Location);
      localStorage.setItem('uploaded_data_path' , data.Location);
      // this._toastr.success("File Upload Faild, Please Try Again!" , "Success"); 
      //not working, gives error that success property is not found.
      // this.spinner.hide();   //Not working
     return true; 
    }
  );
  }
}

Solution

  • You are trying to access this within a function() block.

    A function creates its own scope, with its own this, effectively overwriting (replacing) the UploadFileService's this.


    To get around this, you can use the ES6 arrow notation functions, which does not create a new scope within the function block:

    bucket.upload(params, (err, data) => {
        ...
        this._toastr.success("File Upload Faild, Please Try Again!" , Success");
        ...
    }