Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

how to return HttpEvent from service to angular component.ts file?

All I am trying to do is show a progress bar on click of download button for which I need to calculate the percentage . so far, I was able to download the file however I am not able to pass the event from service file.Here is the code I am trying...

Either I would like to calculate the percentage in service file or just pass the event from here to the component.ts file

getBlobChunk(fileSize: number, userRole: String, inFileName: String, inFilePath: String) {
let chunks = [{}];
const chunkSize = 1024 * 1024 * 20; // 20 MB each chunk
let j = 0;
for (let index = 0; index < fileSize; index += chunkSize + 1) {
chunks[j++] = { startRange: index, endRange: index + chunkSize > fileSize ? fileSize : index + chunkSize };
console.log(chunks)
}
let headers = [];
for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
const chunk = chunks[chunkIndex];
const rangeVal = 'bytes=' + chunk['startRange'] + '-' + chunk['endRange'];
console.log('rangeVal',rangeVal);
const httpHeaders = new HttpHeaders().append('startrange', chunk['startRange']).append('endrange', chunk['endRange']);
headers.push(this.httpClient.post(url, {
userrole: userRole,
srcfileName: inFileName,
srcfilePath: inFilePath
}, { headers: httpHeaders, responseType: 'blob',reportProgress: true, observe: 'events' }).pipe(
map((event: any) => {
if (event.type == HttpEventType.DownloadProgress) {
console.log( Math.round((100 / event.total) * event.loaded));
} 
})
));
}
return forkJoin(headers); }
question from:https://stackoverflow.com/questions/65645530/how-to-return-httpevent-from-service-to-angular-component-ts-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can save the current calculated result in some field on the service itself.

then use binding from component html directly to the service

like

transfer-service.ts

export class SomeComponent
{
    public downloadStatus: number;

    updateDownload(currentPercentage: number)
    {
         this.downloadStatus = currentPercentage;
    }
}

some-component.ts

export class SomeComponent
{
    constructor(public service: TransferService)
    {
    }
}

some-component.html

<progressBar [value]="this.service.downloadStatus">
...
</progressBar>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...