如何使第三方javascript函数使异步行为像angular2 http请求?

时间:2017-06-03 10:45:35

标签: javascript angular http amazon-s3

我正在使用AWS-SDK将图像上传到S3存储桶。我这样做是因为据我所知,没有一个angular4库。该功能看起来像这样......

  public uploadImageToS3(fileInput:any, imageNumber){


    let AWSService = (<any> window).AWS;
    let file =  fileInput.target.files[0];

    let fileNameAdjusted = this.imagePathService.getRandomString()+file.name;

    AWSService.config.accessKeyId = "access key";
    AWSService.config.secretAccessKey = "secret access key";
    var s3 = new AWSService.S3({signatureVersion:'V4'});
    let bucket = new AWSService.S3({params:{Bucket:"bucket name"}, signatureVersion:'v4', ContentType: 'image/jpeg', ACL: 'public-read'});

    //I think the Key value is the name of the file to be written to S3, but not sure.
    let params =  {Key:fileNameAdjusted, Body:file};
    bucket.upload(params, function(error, res){

        console.log(imageNumber);
        console.log(res);
        console.log(error);
        if(error!=null && imageNumber==1){
          return res;
        }
        else{
          return error;
        }

      }
    );

  }

此函数不起作用,因为我无法从这样的异步请求中返回值。如何以与使用纯角函数发出http请求类似的方式返回这些值?

当使用angular4&#39; toPromise()&#39;在http请求中使用,然后是&#39; then()&#39;充当回调处理程序的函数。无论如何在angular4 app中使用上面的javascript代码获得此行为/功能吗?

1 个答案:

答案 0 :(得分:0)

你需要修改bucket.upload看起来像这样。

bucket.upload({params, function(err, data) {
if (err) {
  return alert('There was an error uploading your photo: ', err.message);
}
// Do Successfull upload scenario
alert('Successfully uploaded photo.');
});

参考:http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-photo-album.html