2

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

1
  • 2
    I think you're on the right track with your latter idea (a single function to perform the call to your service as well as navigating the route). The only recommendation I would make is to wait for the transaction to complete successfully before performing the navigation, that way you can indicate any errors that might occur. Commented Aug 19, 2021 at 12:55

3 Answers 3

2

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

this.router.navigate(['/link]).then(() => {
 this.service.setData(data);
});
Sign up to request clarification or add additional context in comments.

Comments

2

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()
    }
}

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.