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

Nou*_*had 3 service components typescript angular

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

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

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

网络服务

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());
}
Run Code Online (Sandbox Code Playgroud)

服务示例代码

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

  }
);
 }
Run Code Online (Sandbox Code Playgroud)

组件代码

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
}
Run Code Online (Sandbox Code Playgroud)

Jac*_*mpi 6

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

服务.ts :

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

组件.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

  }
);
 }
Run Code Online (Sandbox Code Playgroud)

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

组件示例:

private canRender = false;

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

与组件相关的 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>
Run Code Online (Sandbox Code Playgroud)