Как дождаться завершения сервисного HTTP-вызова в компоненте - PullRequest
0 голосов
/ 01 июля 2018

У меня есть служба, в которой я отправляю HTTP-запрос в веб-API и жду ответа. Я вызываю эту сервисную функцию в 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
}

1 Ответ

0 голосов
/ 01 июля 2018

Я предлагаю вам переместить логику и переменные из сервиса в компонент.

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