title: How to run function when angular component is rendered?
body: <p>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.</p>
  
  <p>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.</p>
  
  <p><strong>app.component</strong></p>
  
  <pre><code>&lt;container&gt;
      &lt;router-outlet&gt;&lt;/router-outlet&gt;
  &lt;/container&gt;
  </code></pre>
  
  <p><strong>container component</strong></p>
  
  <pre><code>&lt;div *ngIf="!userService.getLoggedInUser()"&gt;
    &lt;login&gt;&lt;/login&gt;
  &lt;/div&gt;
  
  &lt;div *ngIf="userService.getLoggedInUser()"&gt;
    &lt;ng-content&gt;&lt;/ng-content&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p><strong>routing module</strong></p>
  
  <pre><code>const routes: Routes = [
    { path: 'myPage', component: myComponent }
  ];
  </code></pre>
  
  <p><strong>my component</strong></p>
  
  <pre><code>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) =&gt; this.data = data);
  
      }
    }
  </code></pre>