ngx-toastr在Angular 5服务的上传功能中不起作用

时间:2018-08-13 12:23:09

标签: angular angular5 toastr

我在Angular 5项目中使用ngx-toastr。我的项目中有一项服务,用于将文件上传到AWS存储桶。

问题是我想在我的服务中使用Ngx-toastr来通知文件是否已成功上传或出现一些错误,但是无法正常工作。谁能帮我吗?

这是我的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; 
    }
  );
  }
}

1 个答案:

答案 0 :(得分:2)

您正在尝试访问this块中的function()

函数使用自己的this创建自己的 scope ,有效覆盖(替换)UploadFileService的{​​{1}}。


要解决此问题,可以使用ES6 arrow notation函数,该函数不会在功能块内创建新作用域:

this