2

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.

onetwothree
  • 672
  • 1
  • 10
  • 20
  • 1
    What does "such as authentication" mean? What should the code do? – Günter Zöchbauer Jan 06 '17 at 13:19
  • 1
    There are lots of ways to do this. You could have a `ReplaySubject` that your components subscribe to, so that they all get the last value received until some logic dictates an update is needed (at which point all subscribers are updated with that, too). You could set something to check whether a value is already present before taking whatever action is needed. – jonrsharpe Jan 06 '17 at 13:26
  • 1
    maybe you are looking for lifecycle-hooks, take a look at https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html. you could fetch user details in `ngOnInit` – Fujiao Liu Jan 06 '17 at 14:20

2 Answers2

4

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
Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
1

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.

Dawid Zbiński
  • 5,521
  • 8
  • 43
  • 70