【问题标题】:How to wait for service HTTP call to finish in component如何在组件中等待服务 HTTP 调用完成
【发布时间】:2018-12-09 23:20:34
【问题描述】:

我有一项服务,我正在向 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());
}

服务示例代码

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

  }
);
 }

组件代码

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
}

【问题讨论】:

标签: angular typescript service components


【解决方案1】:

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

Service.ts:

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

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

【讨论】:

  • 谢谢它解决了我的问题。但是你能解释一下,如果把逻辑放在服务中是不好的,或者这只是一种趋势..
  • 据我所知,这是一种不好的做法,因为通常服务由各种组件共享,如果您输入一些逻辑,在某些情况下可能不需要这种逻辑对于某些组件。还有一次,一位智者告诉我“这是 MVC 模式,组件做逻辑,服务只是 http 调用和 Guard 的东西”
猜你喜欢
  • 2019-11-19
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 2018-07-19
相关资源
最近更新 更多