0

I have a service that has a method for checking if the user is valid or not.

auth.service:

checkUserValidity(): boolean {
  this.isValidUser().subscribe(response => {
    console.log('user valid response');
    console.log('response');
    return true;
  }, (error: AppError) => {
    console.log('error in checkUserValidaty');
    console.log(error);
  });
  return false;
}

isValidUser(): Observable<any> {
  const requestUrl = environment.gatewayUrl + environment.authorizationService + environment.userServiceEndPoint;
  return this.httpClient.get(requestUrl).catch(this.errorService.handleError);
}

And then there is another class, which is calling this service:

if (this.authService.isLoggedIn() && this.authService.checkUserValidity()) {
  return true;
}

The problem is that checkUserValidity(): always returns false, because it doesn't work in an async way. I need to be able to determine if the observable completed without errors, or not and for the checkUserValidity() to complete only after it has completing evaluating the Observable result.

Deniss M.
  • 3,617
  • 17
  • 52
  • 100
  • 3
    isValidUser() never returns false. It returns an Observable. checkUserValidity(), which you never use in the posted code, always returns false. You can't return a boolean if you need an asynchonous call to determine the validity. It's impossible. All you can return is an Observable or a Promise. – JB Nizet Oct 26 '17 at 13:33
  • @JBNizet I made a mistake in my method naming. That is corrected. You also stated the same `impossible` during my other question and that was answered by another person, who seemed to be more competent. May I please ask you to ignore my questions, there is hardly any value in your comments to them. You are wasting my time. – Deniss M. Oct 26 '17 at 13:35
  • 1
    There is no need for such harsh words, we are all here voluntarily and not obliged to help you, so what you should be is thankful that someone takes time to look at your questions. Don't know what previous question you are talking about, so cannot comment, somtimes we all make mistakes in comments and answers tho (if that was the case at that time). But I'm with @JBNizet on this one. The comment is correct. Also since your edit, you are **still not** calling `checkUserValidity()` anywhere. – AT82 Oct 26 '17 at 14:52
  • @AJT_82 I adjusted the initial post. – Deniss M. Oct 26 '17 at 15:23
  • @DenissM. well, as mentioned in comments, you need to return an Observable (or Promise) from service and subscribe to that in your component. – AT82 Oct 27 '17 at 07:33
  • I found a solution here: https://stackoverflow.com/questions/42543799/angular2-route-guard-returning-observablebool-how-to-handle-errors – Deniss M. Oct 27 '17 at 07:34

0 Answers0