When transitioning between views in Angular App, it freezes due to the large data response from an HTTP request

I am encountering an issue with my Angular 9.1.11 application where it freezes after navigating from one page to another (which belongs to a different module with lazy loading).

Here is the scenario:

  • There is an action button called View Report that redirects to a different route, let's say /reportData, with query parameters like

    /reportData?reportId=XYZ&reportDate=YZX
    .

  • In my ReportComponent, I extract the query parameters from ActivatedRoute and use them to make an HTTP request.

  • The HTTP response contains a heavy payload of minimum 4-5 mb.

When I click on View Report, the page freezes for a few seconds before redirecting to

/reportData?reportId=XYZ&reportDate=YZX
and then hitting the HTTP call.

Additional information:

  • I have added timers using Console.time() to track where the freeze occurs.
viewReport: 0.004150390625ms Start                                               --> from page One
viewReport: 186.335205078125ms Report - OnInit                                   --> Freezed
viewReport: 17733.464111328125ms Report - After ViewInit
viewReport: 17754.35009765625ms - viewReport fetchHttp Inital                    --> HttpRequest with upto 4-5 mb response
viewReport: 23164.468994140625ms Report - viewReport fetchHttp subscribed
viewReport: 23188.69091796875ms Report - fetchHttp subscribed End
viewReport: 23188.951904296875ms End

The problematic components are as follows:

Page One:

viewReport(reportForm: FormArray | FormGroup) {
    console.time("viewReport");
    console.timeLog("viewReport", "Start");
    const queryParams: Params = {
        reportId: reportForm.get("reportUuid").value,
        reportDate: reportForm.get("reportDate").value
    };

    this.router.navigate(["/reportData"], {
        queryParams,
        queryParamsHandling: "merge" // remove to replace all query params by provided
    });
}

Report Component:

@Component({
selector: "kt-report-view",
templateUrl: "./report-view.component.html",
styleUrls: ["./report-view.component.scss"],
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [ReportService]
})
export class ReportViewComponent implements OnInit, OnDestroy, AfterViewInit {

reportData: string;

reportLoader$: BehaviorSubject<boolean> = new BehaviorSubject(false);

private reportId: string;
private reportDate: any

constructor(
    private router: Router,
    private reportService: ReportService,
    private activatedRouter: ActivatedRoute
) {}

ngOnInit() {
    console.timeLog("viewReport", "Report - OnInit");          // Freezes Here
    const bodyName = document.getElementsByTagName("body")[0];
    bodyName.classList.add("bg-white");
}

ngAfterViewInit(): void {
    console.timeLog("viewReport", "Report - After ViewInit");
    this.activatedRouter.queryParams.subscribe(
        (res: { reportId: string; reportDate: any }) => {
            if (res) {
                this.reportId = res.reportId;
                this.reportDate = res.reportDate;
                this.fetchReportData();                        // calling HTTP Request
            }
        }
    );
}

ngOnDestroy(): void {
    const bodyName = document.getElementsByTagName("body")[0];
    if (bodyName.classList.contains("bg-white")) {
        bodyName.classList.remove("bg-white");
    }
}

fetchReportData() {
    console.timeLog("viewReport", "Report - viewReport fetchHttp Inital");
    this.reportLoader$.next(true);
    this.reportService.getReportData(this.reportId, this.reportDate).subscribe(
        async (report: any) => {
            console.timeLog("viewReport", "Report - viewReport fetchHttp subscribed Inital");

            const data: any = await this.constructOverAllHtml(report);

            console.timeLog("viewReport", "Report - fetchHttp subscribed End");

            this.reportData = data;
            this.reportLoader$.next(false);

            console.timeEnd("viewReport");
        },
        (err) => {
            this.reportLoader$.next(false);
            console.log(err);
        }
    );
}

private constructOverAllHtml(report: any): Promise<any> {
    return new Promise((resolve, reject) => {
        let finalContent: string = "";
        const mainReportHTML = report.mainReport.reportHTML;

        finalContent = mainReportHTML;
        if (report.childReport)
            report.childReport.map((reportData: any, index: number) => {
                finalContent += ` <p>&nbsp;</p><p><strong>Child Report:
                 ${index + 1}</strong></p> ${reportData.reportHTML}`;
            });
        resolve(finalContent);
    });
}

}

Answer №1

Why are you transferring such a large amount of data with route params? It is not recommended to pass huge amounts of data with route params or query strings, whether it's for a single route or multiple routes. It is better to only pass small and essential data like simple strings, small objects, or arrays.

Here is my suggestion:

  1. Instead of passing data in the route, consider saving it in local storage or session storage. This way, you can easily retrieve 4-5mb of data when needed.
  2. Data stored in the route will only be available as long as the 'angular session' lasts (since it is a single page application). If you refresh the page, Angular will lose the stored data. Additionally, if the route fails, your data will be lost!
  3. By storing the data in local storage, you can access it at any point during the application run. You can also encode your data using the atob() method for security purposes. Don't forget to delete the data once you're done using it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

unable to employ angular ui-sortable

I got the most recent source code from https://github.com/angular-ui/ui-sortable. However, I am facing issues in using it. The demo.html file seems to be broken. Update: Upon inspecting the console when opening demo.html: Navigated to https://www.google. ...

Can PHP encode the "undefined" value using json_encode?

How can I encode a variable to have the value of undefined, like in the JavaScript keyword undefined? When I searched online, all I found were results about errors in PHP scripts due to the function json_encode being undefined. Is there a way to represent ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

Is it possible to integrate ngx-translate with database-supported translations?

I am managing a vast database (pouchDB) that stores translations, with each language having its own dedicated database. How can I leverage ngx-translate to easily access these translations directly from the database? ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

Creating a fantastic Image Gallery in JavaScript

As I work on creating a basic gallery page with html and css, everything seemed to be running smoothly. However, upon testing it in Google Chrome and IE, the onmouseover function is not responding as expected. The idea is for a larger image to display in t ...

Issue encountered while retrieving data from a json server using Angular (HttpErrorResponse)

I've been working on creating a task app for practice, and my goal is to retrieve all the task data from a JSON server. However, I'm encountering an issue where the data doesn't display in the browser console as expected, and instead, an err ...

A visually stunning image showcase with dynamic resizing and strategically placed white spaces using the m

I'm attempting to create a responsive image gallery using the Masonry jQuery plugin, but despite reading numerous articles and forum posts on the topic, I can't seem to get it to work properly. The gallery is displaying many blank spaces. My app ...

What is the best way to include multiple views in a main HTML template in Angular?

Is there a way to load two HTML files into a base HTML file? Essentially, I have a base HTML file with a header and content view, and I want to load different HTML files into each of them. Here is the base HTML file structure: <div class="container"> ...

Retrieve the current system datetime with just a click of a button

Does anyone know how to use JSF + RichFaces to automatically display the current date and time in an inputText field when a button is clicked? Any guidance on this would be greatly appreciated. Thank you! ...

Combining an Image with a CanvasJS Graph and Generating a Downloadable Image of the Composite

I am attempting to combine an image (a background image for my graph) with my canvasJS chart. Once these elements have been merged on a canvas, I aim to obtain a DataURL of this canvas, enabling me to download an image of it (depicting the graph along wit ...

The "maxfilesexceeded" event in dropzone.js does not seem to be triggered when adding files programmatically

In my Vue.js project, I am using dropzone with the maxFiles: 1 option set. To display an existing file from the server in dropzone, I have added the following code: let mockFile = { name: 'Filename', size: file.size }; myDropzone.emit('added ...

Are there any straightforward methods to fully freeze an object along with all its descendants in JavaScript (Deep Freeze)?

Often when passing an object as a parameter, functions may access the object by reference and make changes to the original object. This can sometimes lead to unwanted outcomes. Is there a way to ensure that an object remains unchanged? I am aware of the Ob ...

JavaScript will continue to run uninterrupted even after refreshing the webpage

Has anyone else encountered the issue of a javascript on a page continuing to run even after the page is refreshed? From what I understand, javascript is single-threaded and should stop running when the page is refreshed. Just to provide some background, ...

Unable to access JQuery Draggable method within partial view

In my partial view, I have multiple Divs that are designed to be draggable using the JQuery UI draggable library. The JQuery scripts are included in the master page, and when I view the partial view on its own, everything works fine. However, when I load ...

Is it possible to deactivate the error message related to "Unable to ascertain the module for component..."?

I recently incorporated a new component into my TypeScript2+Angular2+Ionic2 project. Right now, I have chosen not to reference it anywhere in the project until it is fully developed. However, there seems to be an error thrown by Angular/ngc stating "Cannot ...

Locate a specific sequence of characters within an array of objects using JavaScript

I am working with an array of objects, where each object contains a string value. My task is to search for a specific substring within the string. [ { "link": "https://www.sec.gov/Archives/edgar/data/1702510/000170251022000084/00 ...

An effective way to eliminate or verify duplicate dates within an array in AngularJS1 is by employing the push() and indexOf() methods

I have successfully pulled EPOCH dates and converted them into strings, but my previous code did not check or remove duplicates. Does anyone have any suggestions on what I can add to accomplish this? The timestamp in this case is the EPOCH date that I re ...

Sending non-textual data within a JQuery ajax POST request

I have encountered an issue related to sending data from a JavaScript application to a Node.js server for database query purposes. Despite trying to find a solution from various sources, I have been unable to resolve it. Here is the code snippet used to s ...

Refresh the page to change the section using vue.js

I am currently working on a website using Laravel and Vue.js. I require two separate sections for the site: Site: https://www.example.com Admin: https://www.example.com/admin Within the resource/js/app.js file, I have included the main components as fo ...