title: How to get a service response before loading a component Angular 4?
body: <p>I have a service that makes request to an api and according to its response I should decide that a component must be loaded or not. but because of a time spent to receive the response, component loads regardless of response status, and after some time (about 0.5 secs) response is received and if the component must not be loaded, we navigate to somewhere else. I don't want the component to be loaded before receiving the response.</p>
  
  <p>I'm using <em>canActivate</em> function from <em>AuthGuard</em> in angular 4 as below:</p>
  
  <pre><code>export class AuthGuard implements CanActivate {
  access = true;
  res: any;
  
  constructor(private router: Router, private routeService: RouteService){}
  
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
      setTimeout(() =&gt; {
          if( !this.exept.includes(this.router.url) ){
              this.routeService.FormOperation(this.router.url).subscribe(item=&gt; {
                  this.res = item;
                  if (this.res.status == 200) {
                      if (this.res.data.Access[1] == false) {
                          this.access = false;
                      }
                      if (this.access == true)
                      {
                         return true;
                      }
                  else {
                      this.router.navigate(['/dashboard']);
                      return false;
                  }
              })
          }
      },0);
  
      if (sessionStorage.getItem('token') &amp;&amp; this.access)
      {
          // logged in so return true
          return true;
      }
  
      // not logged in so redirect to login page with the return url
      this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
      return false;
  }
  </code></pre>
  
  <p>I'm using <em>setTimeout</em> so that I can get a correct <em>this.router.url</em> . </p>
  
  <p>Update:</p>
  
  <p>I added resolver as below:</p>
  
  <pre><code>resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): void {
  
      this.routeService.FormOperation(this.router.url).toPromise()
          .then(response =&gt; {
              this.form_operation_data = response;
  
              if(!this.form_operation_data['data']['Access'][1]) {
                  this.router.navigate(['/dashboard']);
              }
          })
          .catch(err =&gt; {
              console.error(err);
          });
  }
  </code></pre>
  
  <p>but still the component loads before response data receives ...</p>