Angular: Using (click) and routerLink on the same Button

Viewed 268

I have a button that redirects to a new page and at the same time should save data to a Service. As I use it now it looks like this:

<button [disabled]="!isValid" (click)="saveToService()" routerLink="/link">Next</button>

Now I wonder if this is best practice. It feels like the html button is somewhat cluttered by so many seperate functionalities. The obvious alternative is to move the router navigation to a function that does both things, as in:

<button [disabled]="!isValid" (click)="saveAndNavigate()">Next</button> and in ts:

private saveAndNavigate():void { this.service.setData(data); this.router.navigate(['/link]); }

Is there a 'right' way to do this? Are there some unwanted side effects from doing both actions in html?

Thanks

3 Answers

I would suggest you to do it in router promises. So you can:

this.router.navigate(['/link]).then(() => {
 this.service.setData(data);
});

I would implement the OnDestroy function in your component, so you can store the data when the component terminates.

Something like this in HTML:

<button [disabled]="!isValid" routerLink="/link">Next</button>

And like this in your component:

import { Component } from '@angular/core';

@Component({...})
export class ThisComponent implements OnDestroy {


    ngOnDestroy(){
        saveToService()
    }
}

If your navigation is performed regardless of the outcome of the service call, then Fatih's answer would work just fine.

On the other hand, and what I've normally seen, is that page navigation should only occur after (successful) completion of the request. If this is the case, I would remove the routerLink directive from your button and keep the (click) function. That function could look like this:


// if your service is making an Http request
public saveToService() {
  this.service.saveStuff().pipe(
    tap(() => this.router.navigate(['/somewhere']))
  )
}

tap simply performs some action without affecting the data stream, so it's perfect for router navigation.

Related