Angular Routing Problem after excel download

632 Views Asked by At

My Routing works if i dont download the excel file but if i download file and then use routing then it fails.

The Line which seems to be problematic is this line:

 **const Excel = require('exceljs');**

This line is inside function which download excel. If I click on the back button, the current page and previous page both are shown on a new page and OnInit and constructor are not hit

<a  (click)="btnClick()" class="btn btn-default cancel-btn">Back</a>

btnClick() {
    this.router.navigateByUrl('/newPage');
};

I have tried this also,

<a  [routerLink]="['/newPage']" class="btn btn-default cancel-btn">Back</a>

But on new page, i can see selector of both pages,

 <oldPage></oldPage>
 <newPage></newPage>

then i tried this:

 I have tried ng Zone code too.

  btnClick() {
    if (this.inTheZone){
       this.inTheZone = false;
       this.ngZone.run(() => {
      this.router.navigate(['/newPage']);
    })
  }
};

My routing code is like this:

const routes: Routes = [
{
  path: 'newPage', component: newPageComponent, data: { title: 'NewPage' }
}]

Please anyone help.

1

There are 1 best solutions below

0
Javier On

Probably your problem as Fmerco has said, is that you are using require, what will give you a crash in your app.

In Angular we use TypeScript and therefore we can use ES2015 at least.

That means that we use the module system from ES2015 that uses import as a keyword to retrieve information from modules.

import { Workbook } from 'exceljs';

And if you want to push a file to the client, you can't use a redirect (because that way you are breaking the SPA concept, and probably the routing), so you probably will want a library like file-saver.

workbook.xlsx.writeBuffer().then((data) => {
      let blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      fs.saveAs(blob, 'CarData.xlsx');
});

You can find a very good tutorial in https://www.ngdevelop.tech/export-to-excel-in-angular-6/ and an example in https://github.com/exceljs/exceljs (are updated to Angular 8).