【问题标题】:ngx-toastr not working inside upload function of Angular 5 servicengx-toastr 在 Angular 5 服务的上传功能中不起作用
【发布时间】:2018-08-13 12:23:09
【问题描述】:

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

问题是我想在我的服务中使用 Ngx-toastr 来通知文件是否上传成功或有一些错误,但它不起作用。谁能帮帮我?

这是我的上传文件服务:

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

【问题讨论】:

  • 在我看来这和调用api没有关系,你正确调用了ToastrService。是否可以在stackblitz.com创建一个例子
  • 见下面杰弗里的回答。这就是导致问题的原因。

标签: angular angular5 toastr


【解决方案1】:

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

函数创建自己的作用域,具有自己的this,有效地覆盖(替换)UploadFileServicethis


要解决这个问题,您可以使用ES6 arrow notation 函数,它不会在函数块内创建新范围:

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

【讨论】:

  • 也许你应该解释一下为什么会这样? (无论如何都赞成)
  • 工作就像一个魅力。谢谢杰弗里。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-12
  • 2015-01-29
  • 1970-01-01
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多