У меня есть служба, в которой я отправляю 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
}