简体   繁体   中英

How to make 3rd party javascript function that makes an asynchronous behave like an angular2 http request?

I am using the AWS-SDK to upload images to an S3 bucket. I am doing this because there is not an angular4 library for this to my knowledge. The function looks like this...

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

      }
    );

  }

This function does not work because I cannot return the values from an asynchronous request like this. How can I return these values in a similar way to making http requests with pure angular functions?

When this is done with angular4 'toPromise()' is used, on the http request, and also the 'then()' function which acts as a callback handler. Is there anyway to get this behavior/functionality with the above javascript code in an angular4 app?

You need to Modify bucket.upload to look like this.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM