0
private hasAccess() {
  let access = false;
  this.login.hasCookie(this.cookieService.get('login')).subscribe(hasCookie => {
    if (hasCookie === 1) {
      this.login.getCookie().subscribe(cookieFromServer => {
        if (cookieFromServer === this.cookieService.get('login')) {
          access = true;
          console.log(access);
        }
      });
    }
  });
  return access;
}

My console.log on line 8 returns true but my function returns false. It's the same variable. Why does it return false? It should be true!

xRay
  • 543
  • 1
  • 5
  • 29
  • 2
    [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Unmitigated Dec 28 '19 at 02:55
  • 2
    It is returning false because your code is asynchronous. This means that your subscription will be executed after your function returns. Wrap your `this.login....` within a Promise, await the promise. – Get Off My Lawn Dec 28 '19 at 02:55
  • @GetOffMyLawn you mean something like this? https://jsfiddle.net/RezaScript/2d1p57qs/ – xRay Dec 28 '19 at 03:38
  • 1
    Pretty close, I would do something more along the lines of this: https://jsfiddle.net/anky6bpv/ – Get Off My Lawn Dec 28 '19 at 03:46
  • @GetOffMyLawn thank you for the code! I have tried it but it still returns false. Is it because I am using an asynchronous function within an asynchronous function? – xRay Dec 28 '19 at 14:20
  • @GetOffMyLawn I have tried it with this code: https://jsfiddle.net/RezaScript/2d1p57qs/1/ and now I finally get `true`. Thank you so much, you helped me a lot! – xRay Dec 28 '19 at 14:42

0 Answers0