简体   繁体   中英

How to use aws-sdk inside webworker of Angular 9?

I installed aws-sdk :- npm install aws-sdk

And then imported aws-sdk inside my worker file like this:

app.worker.ts :- import * as AWS from 'aws-sdk';

And then tried to console.log inside addEventListener code is here:-

    addEventListener('message', async ({ data }) => {
    console.log(AWS);
}

After doing this i am getting errors as in screenshot:

在此处输入图像描述

I also tried to solve this error for that i defined global in polyfills.ts though it's not working

polyfills.ts :- (window as any).global = window;

Any help will be greatly appreciated. What i am trying to achieve is i am trying to upload file from worker using aws-sdk to s3 from my angular project. Thank you guys!

It may help for others too so I am giving the solutions how I solved the issue:-

Web Workers don't have a global window object. So to access the global object we can use self instead.

So to solve my problem I followed these steps:

Steps:-

  • In the app.worker.ts , To use the Type-Script definition files with the global AWS object in a front-end project. We have to add reference types at the top of the worker file eg /// <reference types="aws-sdk" /> .

  • Define window const window = self;

  • And after the that import aws-sdk scripts importScripts('assets/js/aws-sdk.js'); then we'll be able to access the AWS object inside addEventListener('message', async ({ data }) => { console.log(window.AWS) });

  • Here i am importing scripts from assets because i had to customized aws-sdk to avoid window not defined error while calling s3.createMultipartUpload()

  • Here is the link https://raw.githubusercontent.com/nyaupane/customized_aws_sdk/master/assets/js/aws-sdk.js of customized aws_sdk in case if your requirement is same as mine otherwise you can customize according as your requirement.

  • Final app.worker.ts will look like this: https://github.com/nyaupane/customized_aws_sdk/blob/master/assets/worker/app.worker.ts

Now it works perfectly for multipart uploading...using aws_sdk in angular9 web worker.

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