简体   繁体   中英

How to handle exceptions when using routerLink in Angular

I have a component with routerLink, and the routing module has a route. The ngOnInit calls a service

this.myService.create(aId).subscribe(
data => { this.ourdata = data;
this.dataSource = new MatTableDataSource<test>(data.some);
},
err => console.error(err),
() => console.log('Done '+ JSON.stringify(this.ourdata))
);

and html shows spinner till data is received

<div *ngif="!ourdata">
<mat-spinner></mat-spinner>
</div>
<div *ngif="ourdata" class="centering-div">
...
</div>

In case I get an exception, how can I show a dialog and stop the spinner? I am looking for change in html template

You can use the err callback of the subscribe.

error: boolean;
.....
this.myService.create(aId).subscribe(
data => { 
   this.ourdata = data;
   this.error = false;
   this.dataSource = new MatTableDataSource<test>(data.some);
},
err => { 
   console.error(err); 
   this.error = true;
   // call method that shows the dialog
   // or show the dialog in the HTML based on the value of error being true
}
() => console.log('Done '+ JSON.stringify(this.ourdata))
);
<div *ngif="!ourdata && !error">
<mat-spinner></mat-spinner>
</div>
<div *ngif="ourdata" class="centering-div">
...
</div>

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