Reputation: 682
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
Reputation: 658027
There are many different ways depending on the concrete requirements:
How to pass parameters rendered from backend to angular2 bootstrap method executes a method before Angular initializes AppComponent
https://angular.io/docs/ts/latest/guide/router.html#!#guards executes before a route is activated
Executes the constructor of MyService
when the AppModule
(or any other module) is initialized
@NgModule(...)
export class AppModule {
constructor(myService:SomeService) {}
}
MyService
when the AppComponent
(or any other component or directive) is initializedclass AppComponent {
constructor(myService:SomeService) {}
}
Upvotes: 4
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