为什么要阻止canActivate总是返回false?

时间:2018-03-20 19:08:18

标签: angular typescript authentication

我一直在搜索,以避免重复发布等,并尝试提供一些解决方案,但没有成功解决问题。

我使用canActivate来保护仪表板,它工作正常,只是它总是返回false,以便我永远无法访问受保护的路由器。

我没有收到任何错误或类似内容,因此我可以进行本地化和修复。 isAuthenticated始终设置为false,但未获得该函数的结果:setAuthenticated()将其更改为:true

请问好吗?

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class AuthService {

    public isAuthenticated = false;

    constructor(private http: HttpClient) {
    }

    setUserLoggedIn() {
        this.isAuthenticated = true;
    }

    getUserLoggedIn() {
        return this.isAuthenticated;
    }

    public setAuthenticated() {

        this.http
            .get<any>(url, {withCredentials: true, observe: 'response'})
            .subscribe(
                (res) => {
                    console.log('Status: Authenticated: ' + res.headers.get('status') );
                    if ( res.headers.get('status') === '200') {
                        this.setUserLoggedIn();
                    }
                },
                err => {});
    }
}

authguard.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate,
         ActivatedRouteSnapshot,
         RouterStateSnapshot,
         Router,
         ActivatedRoute} from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
import { AuthService } from './service/auth.service';


@Injectable()
export class AuthguardGuard implements CanActivate {
    constructor(
        private user: AuthService,
        public router: Router,
        private http: HttpClient,
        private activatedRoute: ActivatedRoute) {
    }

    canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

        if ( !this.user.isAuthenticated ) {
            console.log('Not authenticated!');
            this.router.navigate(['userLogin']);
            return false;
        }
        return true;
    }
}

1 个答案:

答案 0 :(得分:1)

最好的方法是在Auth-Guard中使用Observable。如下所示:

在auth.service.ts中,更改“setAuthenticated”方法,如下所示。

public setAuthenticated() {
// YOU SHOULD SET "isAuthenticated" value to FALSE when the session is over.
if (this.isAuthenticated === true) {
    return Observable.of(true);
} else {
    return this.http.get<any>(url, {withCredentials: true, observe: 'response'})
      .map((res) => {
        if ( res.status === 200) {
             this.isAuthenticated = true;
             return true;
        } else {
            this.isAuthenticated = false;
            console.log('Not authenticated!');
            this.router.navigate(['userLogin']);
            return false;
        }
    });
}
}

authguard.guard.ts:

// All imports
@Injectable()
export class AuthguardGuard implements CanActivate {
constructor(
    private user: AuthService,
    public router: Router,
    private http: HttpClient,
    private activatedRoute: ActivatedRoute) {
}

canActivate(): Observable<boolean> {
   return this.user.setAuthenticated()
     .map((res) => {
        if ( res === true) {
             return true;
        } else {
            console.log('Not authenticated!');
            this.router.navigate(['userLogin']);
            return false;
        }
    });
  }
}