MyComponent uses a service to get data then renders that data. However, the service cannot get data until the user is logged in. If the user goes to the route '/myPage' for the first time, the container component will display the login component. However, even though login component is rendered instead of ng-content (which evaluates to MyComponent), MyComponent is initialized by angular and fetches and causes the service to fetch data too early, before logging in. Therefore when the user successfully logs in and MyComponent finally renders, there's no data the initial data service returned nothing.
How can I postpone the data fetching until after the component is rendered? I've tried all the different lifecycle methods inside MyComponent without success.
app.component
<container>
<router-outlet></router-outlet>
</container>
container component
<div *ngIf="!userService.getLoggedInUser()">
<login></login>
</div>
<div *ngIf="userService.getLoggedInUser()">
<ng-content></ng-content>
</div>
routing module
const routes: Routes = [
{ path: 'myPage', component: myComponent }
];
my component
export class MyComponent {
data
constructor(private dataService: DataService) {}
ngOnInit () {
//how can i make run this service AFTER the component renders? i know
//ngOnInit is definitely not the correct lifecycle method, but what is?
this.dataService.get().then((data) => this.data = data);
}
}