首页 > 解决方案 > 在 Angular 6 中运行有角度的打字稿代码

问题描述

我有 POST 到 Web 服务的代码,并在一小段延迟后反复轮询状态更新。为了避免垄断浏览器的主线程,我想把这段代码放在一个 web worker 中。如果这只是一个简单的 Javascript,我可以弄清楚。但是,我在 Angular 6 环境中运行它。我无法升级到在 CLI 中支持 Web Worker 的 Angular 8,这在很大程度上是由于依赖冲突。此外,该服务是用 Typescript 编写的,并使用来自 @angular/common/http 的 HttpClient 之类的东西来进行 REST 调用。一些页面谈论做一些单独的 WebPack,其他人使用这个 ngx-web-worker 库,大多数假设你使用的是最新的 Angular。

我对 Angular 和 Node 有点陌生,但不想做一些不明智的事情。话虽如此,我需要它相当简单,而不需要我阅读 50 页来弄清楚如何去做。我本来以为 Angular 在 V6 中解决了这个问题,所以我假设有一个我不知道的简单解决方案。

下面是我想做网络工作者的组件。请参阅 onChooseBlueReportFile() 方法:

import { Component, OnInit, Input } from '@angular/core';
import { reloadW3dsScript } from '../../../../shared/utils/w3ds.util';
import { SoftlayerService } from '../../../../core/services/softlayer.service';
import { SpringBatchJobExecutionStatus } from '../../../../shared/models/SpringBatchJobExecutionStatus';

@Component({
    selector: 'app-report-uploader',
    templateUrl: './report-uploader.component.html',
    styleUrls: ['./report-uploader.component.css']
})
export class ReportUploaderComponent implements OnInit {
    blueReportFile: File;
    blueReportSelected = true;
    blueReportFileName: string;
    softLayerCostFilePercentUploaded: number = 0;
    showLoaderBlueReport = false;
    successBlueReport = false;
    responseBlueReport = '';
    stillProcessing: boolean = false;
    errorBlueReport = false;
    errorMessageBlueReport: string = '';
    uploadErrorTitleBlueReport: string;
    uploadErrorToDisplayBlueReport: any;
    @Input() uploaderStatus: string = 'NOTHING_SELECTED';

    constructor(private softlayerService: SoftlayerService) {
        this.blueReportFileName = 'No file selected';
    }

    ngOnInit() {
    }

    ngAfterContentInit() {
        reloadW3dsScript();
    }

    sleep(ms: number) {
        return new Promise((resolve) => {
            setTimeout(resolve, ms);
        });
    }

    async onChooseBlueReportFile(files: FileList) {
        console.log('@@@ onChooseBlueReportFile');
        this.blueReportSelected = true;
        this.blueReportFileName = files.item(0).name;
        this.blueReportFile = files.item(0);
        const pattern = /\d*[0-9]+[.]+\d{3}[0-9]$/;
        if (this.blueReportFileName == null || this.blueReportFileName == 'No file selected') {
            this.uploaderStatus = 'ERROR';
            this.displayUploadBlueReportsError('No file selected.Please select one.');
        } else {
            this.uploaderStatus = '';
            this.errorBlueReport = false;
            if (!this.errorBlueReport) {
                this.showLoaderBlueReport = true;
                (async () => {
                    this.softlayerService.postAsyncFiles(this.blueReportFile)
                        .subscribe(postAsyncFilesData => {
                            this.uploaderStatus = 'UPLOADING';
                            console.log('Post async cost file Received ' + postAsyncFilesData);
                            var errorDetected = false;
                            var jobExecutionResult: SpringBatchJobExecutionStatus = postAsyncFilesData;
                            var counter = 0;
                            console.log(JSON.stringify(jobExecutionResult));
                            if (jobExecutionResult.exitStatus === 'RUNNING' || jobExecutionResult.batchStatus === 'STARTING') {
                                console.log('Beginning jobExecutionResult fetch loop');
                                while (jobExecutionResult.batchStatus === 'RUNNING' || jobExecutionResult.batchStatus === 'STARTING' && counter < 10) {
                                    counter++;
                                    console.log('@@@ jobExecutionResult=' + JSON.stringify(jobExecutionResult));
                                    this.showLoaderBlueReport = false;
                                    this.stillProcessing = true;
                                    //this.softLayerCostFilePercentUploaded = jobExecutionResult.percentComplete;
                                    this.softLayerCostFilePercentUploaded += 10;
                                    console.log('Before sleep');
                                    this.sleep(10000);
                                    console.log('After sleep');
                                    this.softlayerService.getAsyncFiles(jobExecutionResult.jobInstanceId, jobExecutionResult.jobExecutionId).subscribe(
                                        (getAsyncFilesData) => {
                                            console.log('Got job execution status ' + JSON.stringify(getAsyncFilesData));
                                            jobExecutionResult = getAsyncFilesData;
                                        },
                                        (error) => {
                                            console.log('Error getting job execution status ' + error);
                                            errorDetected = true;
                                            this.uploaderStatus = 'ERROR';
                                            this.showLoaderBlueReport = false;
                                            this.displayUploadBlueReportsError(error, 'File upload failed');
                                        }
                                    );
                                    console.log('After end jobExecutionResult fetch loop');
                                } /* end while */
                                console.log('After loop fetching status execution status ' + jobExecutionResult.exitStatus);
                                console.log('After loop fetching error ' + errorDetected);

                            } else {
                                console.log('Not entering check loop batchStatus='+jobExecutionResult.batchStatus+' exitStatus='+jobExecutionResult.exitStatus);
                            }
                            this.showLoaderBlueReport = false;
                            this.successBlueReport = true;
                            this.blueReportFileName = "No file selected";
                            this.blueReportSelected = false;

                            /** TODO Tap parent container for this function */
                            //this.getCurrentUserFiles();
                        },
                            (error) => {
                                this.uploaderStatus = 'ERROR';
                                this.showLoaderBlueReport = false;
                                this.displayUploadBlueReportsError(error, 'File upload failed');
                            });

                }
                )();
            }
        }
    }

    displayUploadBlueReportsError(error: any, title?: string) {
        this.errorBlueReport = true;
        this.responseBlueReport = '';
        this.successBlueReport = false;
        this.uploadErrorTitleBlueReport = title;
        this.uploadErrorToDisplayBlueReport = error;
    }

}

谢谢,樵夫

标签: angulartypescriptweb-worker

解决方案


推荐阅读