0

Is there a way to setup common ngOnInit() to be executed on every single page in Angular application? Instead of writing in each and every page:

import { AppComponent } from '../app.component';

constructor(
    private app: AppComponent) {}

ngOnInit(): void {
    this.app.doCommonStuffForEachPage();
}

I would like to simply write this code once, and when router opens each page, this.app.doCommonStuffForEachPage() would be called.

Dalibor
  • 1,430
  • 18
  • 42
  • 2
    If you are only talking about routed components you can use router events https://angular.io/guide/router#router-events You can also make a parent components that you inherit in all other components – Shadowlauch Jan 04 '18 at 13:42
  • That's what I was looking for, thx – Dalibor Jan 04 '18 at 13:47

2 Answers2

2

Thanks to Shadowlauch, I came up with this solution:

import { AppComponent } from '../app.component';
import { Router, NavigationEnd } from '@angular/router';

constructor(
    private app: AppComponent,
    private router: Router) {

 router.events.subscribe(event => {
    if (event instanceof NavigationEnd) {
        this.app.doCommonStuffForEachPage();
    }
 });
}
Dalibor
  • 1,430
  • 18
  • 42
  • 1
    That's not an answer to the question, though. It's basically what I've stated in [my answer](https://stackoverflow.com/a/48096614/2131286): "Take a step back and think about what you're trying to solve." – Lazar Ljubenović Jan 04 '18 at 13:51
  • please edit your answer (just formally) so I can undo the downvote – Dalibor Jan 04 '18 at 13:59
1

Although there's probably a hackish way to do this, it's bad design. So I'd say the answer is no, at least not in a way that it's also good practice.

If all components are doing something globally, it's like a magic function that's called out of nowhere. Everyone who comes across your codebase has to know this fact, otherwise weird stuff will start to happen. Plus, what happens when you want a component that does not have this behavior? It's gonna happen sooner or later.

You've already encapsulated the behavior in a function that's in an injectable class, which makes it reusable across different components. That's good enough. Call it on your own every time you need it.

I can't really imagine a situation where this would be needed, though. What could a simple UI button component have in common with an AppComponent that holds the whole page together? Take a step back and think about what you're trying to solve. Calling a function automagically every time a component is initialized is a bad solution. Which is why it is impossible.

Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91