How to wait for service HTTP call to finish in component

16,565

I suggest you to move the logic & the variables from service to component.

Service.ts :

function tryLogin(...put here your args): Observable<any> {
   return this.webService.isTokenValid(jsonStr);
   // Yep, just this. Usually services don't handle logic.
}

Component.ts :

this.tokenService.verifyAccessToken("","/welcome", true)
.subscribe(
  data => {
    isAccessTokenValid = data["AccessValidation"]; 
    console.log("TOKEN SERVICE => isValid: "+isAccessTokenValid);
    // success connection

    if(!isAccessTokenValid){
      // access token is not valid now we will send refresh token
      console.log("=> Access token is not valid sending refresh token... ");


      if(inverse) this.router.navigate([invalidDest]);

    }
    else{
      // access token is valid so we can continue operation
      if(!inverse) this.router.navigate([invalidDest]);

    }

  },error => {
    console.log("Error while validating token");

  },
  () => {
    // 'onCompleted' callback.
    // No errors, route to new page here

  }
);
 }

Anyway you can do something like that to prevent the page render before the subscription has finished:

Component example:

private canRender = false;

ngOnInit(): void {
   this.service.login(...)
   .subscribe( data => {
      //do Stuff
      this.canRender = true;
   });
}

related html to component :

<div ngIf="canRender">
   Content here will be render when you have the data you needed
   <!-- that when the line "this.canRender = true;" will be executed
</div>
Share:
16,565
Nouman Arshad
Author by

Nouman Arshad

Updated on June 05, 2022

Comments

  • Nouman Arshad
    Nouman Arshad over 1 year

    I have a service in which i'm sending HTTP request to the web api and waiting for response. I'm calling this service function in ngOnInit().

    I want component to wait for service call to finish and depending upon the HTTP response i should redirect user.

    Problem I call service function and component does not wait for it to finish and renders the page on screen then after 2 3 seconds it correctly redirects.. I don't want it to render..

    web service

    isTokenValid(token: any){
    
    const body = token;
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://'+this.web_url+':'+this.web_port+'/api/Authentication', body, {
      headers: headers
    })
    .map((data: Response) =>data.json());
    }
    

    service exampe code

    verifyAccessToken(vaildDest: String, invalidDest: String, inverse:Boolean){
    var localStorageObj = localStorage.getItem('currentUser');
    
    if(localStorageObj == null){
      // no user details present in browser
    
      if(inverse) this.router.navigate([invalidDest]);
      return;
    
    }
    
    var currentUser = JSON.parse(localStorageObj);
    var token = currentUser.AccessToken;
    var email = currentUser.Email;
    var isAccessTokenValid = false;
    console.log(token);
    var jsonStr = {
      "AccessToken": token,
      "Email": email
    }
    this.webService.isTokenValid(jsonStr)
    .subscribe(
      data => {
        isAccessTokenValid = data["AccessValidation"]; 
        console.log("TOKEN SERVICE => isValid: "+isAccessTokenValid);
        // success connection
    
        if(!isAccessTokenValid){
          // access token is not valid now we will send refresh token
          console.log("=> Access token is not valid sending refresh token... ");
    
    
          if(inverse) this.router.navigate([invalidDest]);
    
        }
        else{
          // access token is valid so we can continue operation
          if(!inverse) this.router.navigate([invalidDest]);
    
        }
    
      },error => {
        console.log("Error while validating token");
    
      },
      () => {
        // 'onCompleted' callback.
        // No errors, route to new page here
    
      }
    );
     }
    

    Component code

    constructor(private router: Router, private tokenService:TokenService) { }
    
    
    ngOnInit() {
      this.tokenService.verifyAccessToken("","/welcome", true);
    
      // i want to stop it here and dont render current component until above call is finished
    }