PBandJ
PBandJ

Reputation: 2883

Angular2 Authguard Redirect Route Not Working

I created an authguard to prevent users who aren't logged in to enter a page. After the authguard runs and returns true, it doesn't redirect to the appropriate page. Am I doing something wrong?

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(
                private authStatusService: AuthStatusService,
                private authService: AuthService,
                private router: Router ) { }

    canActivate(): any {

        return this.authStatusService.authStatus.subscribe(i => {
            if(i === 'auth-login-success') {
                return Observable.fromPromise(this.authService.getUser())
                    .subscribe(res => {
                        if(!res.id) {
                            this.router.navigate(['summary']);
                            return Observable.of(false);
                        }
                        return Observable.of(true);
                    },
                    error => {
                        return Observable.of(false);
                    })
            } else {
                console.log('user has not logged in')
                this.router.navigate(['login']);
                return Observable.of(false);
            }
        })
    }
}

Upvotes: 2

Views: 874

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657068

Something like that should work:

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(
                private authStatusService: AuthStatusService,
                private authService: AuthService,
                private router: Router ) { }

    canActivate(): any {

        return this.authStatusService.authStatus
        .mergeMap(i => {
            if(i === 'auth-login-success') {
                return this.authService.getUser())
                    .map(res => {
                        if(!res.id) {
                            this.router.navigate(['summary']);
                            false;
                        }
                        return true;
                    })
                    .catch(error => {
                        return false;
                    })
            } else {
                console.log('user has not logged in')
                this.router.navigate(['login']);
                return false;
            }
        })
        .first() // not sure if this line is still necessary
    }
}

The router expects a boolean, Promise<boolean> or Observable<boolean>. When you call subscribe() you get a Subscription which won't work. With map() an Observable is returned.

Upvotes: 1

Related Questions