0

How can you return a value from a promise and include it in a global variable?

I'm trying to make this formed, but to no avail. The global variable is undefined

import { Injectable } from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, CanLoad, Route, Router, RouterStateSnapshot} from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Auth } from '../providers/auth';

@Injectable()
export class AuthGuard implements CanActivate, CanLoad {

    _check: boolean;

    constructor(private auth: Auth, private router: Router) {
        console.log(this.check());

    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
        return this.check();
    }

    canLoad(Route: Route): Observable<boolean> | boolean {
        return this.check();
    }


    check() {

        this.auth.check().then((user) => {
            if (!user) {
                this._check = null;
            }else {
                this._check = true;
            }
        });


        console.log(this._check)  <---- undefined
        return this._check;
    }
}
phuclv
  • 37,963
  • 15
  • 156
  • 475
marcelo.delta
  • 2,730
  • 5
  • 36
  • 71

1 Answers1

0

No need to do if/else. If promise resolves(hence got the user) it'll go to then block.

It looks like this.auth.check() is returning a promise. So, this should work.

this.auth.check()
            .then((user) => {
               return true;
            },
            .catch((err){
               return false;
            });

And your console.log(this._check) statement is executing berfore the promise resolves or rejects, that's why you are getting undefined.

If you are new to promise. Please check out this and/or this

nightElf91
  • 650
  • 1
  • 7
  • 28