0

I am using router change observer in different components. I would like to have it reusable so I dont need to include this code into every component that needs it. How could I achive this?

changeObserver = null; constructor(private router: Router) { this.changeObserver = router.events.pipe( filter(event => event instanceof NavigationEnd) ).subscribe((event: NavigationEnd) => { if(event instanceof NavigationEnd) // change of url //-- // call some component functions - different for each component //-- }); } ngOnDestroy() { this.changeObserver.unsubscribe(); } 

2 Answers 2

1

You can create a separate Service class to handle this small piece of code and will give you option of callback which will handles the async operations.

NavigationService

@Injectable() export class NavigationService { private changeObserver; constructor(private router: Router) { } execute(callback) { this.changeObserver = router.events.pipe( filter(event => event instanceof NavigationEnd) ).subscribe((event: NavigationEnd) => { if (event instanceof NavigationEnd) callback(); }); } } 

In Component

constructor(private NavigationService: navigationService) { this.navigationService.execute(()=>{ //your code goes here. }); } 

Note : The code is written in stackoverflow editor directly so there could be some typo and syntactical error. Please correct yourself.

Sign up to request clarification or add additional context in comments.

3 Comments

Looks good, but how do I unsubscribe after I leave this component and want same functionality on the other? With this setup callbacks are adding to each other.
Already solved it. Removed from app.module providers and added into component providers. Also added ngOnDestroy() { ...unsubscribe(); } into service. Service singleton was the problem. Is there any problem with solution like this?
That is absolutely fine.👍
0

You could make an abstract class which implements what you want and extend the ones you want to have that routing implementation.

abstract class BaseComponent { observer; constructor() { this.observer = [1, 2, 3].forEach(number => { this.do(number); }); } onDestroy() { // this.observer.unsubscribe(); } abstract do(number); } 

And implement:

class Component extends BaseComponent { do(number) { console.log(number); } } 

1 Comment

Thanks for answer, but since I'm already extending component with other class, I went with service solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.