如何在组件中等待服务HTTP调用完成

时间:2018-07-01 14:25:54

标签: angular typescript service components

我有一项服务,我正在向Web api发送HTTP请求并等待响应。我在ngOnInit()中调用此服务函数。

我希望组件等待服务调用完成,并且根据HTTP响应,我应该重定向用户。

问题 我打电话给服务函数,组件不等待它完成并在屏幕上呈现页面,然后在2 3秒后正确重定向。.我不希望它呈现。.

网络服务

smtp_header_checks

服务样本代码

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());
}

组件代码

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

  }
);
 }

1 个答案:

答案 0 :(得分:2)

我建议您将逻辑和变量从服务移至组件。

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

  }
);
 }

无论如何,您都可以执行类似的操作以防止在订阅完成之前呈现页面:

组件示例:

private canRender = false;

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

与组件相关的html:

<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>