onetwothree
onetwothree

Reputation: 682

How can I run code only when the app first loads?

I remember seeing in the docs that you could have code, such as authentication, be run only when the app first loads. Unfortunately for me I cannot find it again despite looking.

In my case, I want to fetch user details, such as name, without having to make an API call every time I request the information.

Upvotes: 2

Views: 4471

Answers (2)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658027

There are many different ways depending on the concrete requirements:

@NgModule(...)
export class AppModule {
  constructor(myService:SomeService) {}
}
  • Executes the constructor of MyService when the AppComponent (or any other component or directive) is initialized
class AppComponent {
  constructor(myService:SomeService) {}
}
  • and others

Upvotes: 4

Dawid Zbiński
Dawid Zbiński

Reputation: 5826

If I understand your question correctly, you can fetch the data in the AppComponent's constructor method.

That means you get the data when the AppComponent si loaded (which is loaded once only, if I'm correct) or if you want the data to be fetched in other component you can use it's constructor() or ngOnInit() method when your class implements OnInit. You just need to do that in the right scope.

Please, remember that you should use services to fetch the data from external sources.

Upvotes: 1

Related Questions