karns
karns

Reputation: 5887

Where to Put App-wide Logic - Angular (2+)

In AngularJS, I just stuck app wide logic in the run.js. For instance:

// runs when the app viewport/window gets focus, such as when switching tabs and back
$window.onfocus = function() {
    redirectIfUserChange(); // or any other arbitrary logic
};

The most similar thing in Angular seems to be the main.ts. However, I'm not sure on the reasons that is a good or bad idea. Perhaps one might suggest running all of this in the root (most parent) component upon init.

Questions

1) What is the best practice for this kind of stuff in Angular (2+)?

2) Are there any other good things to be aware of when attempting to incorporate app wide logic?

Upvotes: 2

Views: 284

Answers (1)

ashfaq.p
ashfaq.p

Reputation: 5487

You can put app wide logic in app.component.ts. It will be first to be initialized and you can put logics needed app-wide here.

Anything which was put in app.run in angularJs can be put in app.component.ts

eg: Things like listening to route events can be put here.

Upvotes: 2

Related Questions