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

问题描述 投票:1回答:1

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

我使用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;
    }
}
angular typescript authentication
1个回答
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;
        }
    });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.