Javascript 在角落里挣扎着穿过AuthGuard

Javascript 在角落里挣扎着穿过AuthGuard,javascript,angular,Javascript,Angular,尝试遵循此处提供的AuthGuard示例: 不幸的是,在尝试实现ActivationGuard.ts文件时,我收到的错误很少 ERROR in C:/Users/app/src/app/ActivationGuard.ts (6,24): Cannot find name 'ActivatedRouteSna pshot'.) C:/Users/app/src/app/ActivationGuard.ts (6,55): Cannot find name 'RouterStateSnapsho

尝试遵循此处提供的AuthGuard示例:

不幸的是,在尝试实现
ActivationGuard.ts
文件时,我收到的错误很少

ERROR in C:/Users/app/src/app/ActivationGuard.ts (6,24): Cannot find name 'ActivatedRouteSna
pshot'.)
C:/Users/app/src/app/ActivationGuard.ts (6,55): Cannot find name 'RouterStateSnapshot'.)
C:/Users/app/src/app/ActivationGuard.ts (13,62): Cannot find name 'CurrentUserService'.)
C:/Users/app/src/app/ActivationGuard.ts (15,31): Cannot find name 'ActivatedRouteSnapshot'.)
C:/Users/app/src/app/ActivationGuard.ts (15,62): Cannot find name 'RouterStateSnapshot'.)
这基本上意味着,
CanActivate
接口和构造函数内部的元素没有定义

路由
文件:

import { WorksheetAccessGuard } from "./ActivationGuard";

const appRoutes: Routes = [
  { path: '', component: LoginComponent }, 
  { path: 'app', component: AppComponent, canActivate: [WorksheetAccessGuard] },
  { path: '**', redirectTo: '' }
];
我的问题是:从哪里可以得到这些缺失的元素

提供我的IDE的图片:(红色的单词是缺少的)

编辑 我做了定制服务。我不确定它是否好:

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

@Injectable()
export class UserAuthenticationService {
    isUserAuthenticated: boolean = false;
    username: string;

    constructor(private http: Http) {
    }

    authentication() {
        this.http.get(`http://localhost/api/auth/isLogged/${this.username}`)
            .subscribe(res => {
                    this.isUserAuthenticated = res.json();
                },
                err => {
                    console.error('An error occured.' + err);
                });
    }


}
现在我在
AuthGuard
文件中收到一些错误:

import { WorksheetAccessGuard } from "./ActivationGuard";

const appRoutes: Routes = [
  { path: '', component: LoginComponent }, 
  { path: 'app', component: AppComponent, canActivate: [WorksheetAccessGuard] },
  { path: '**', redirectTo: '' }
];

**我的主要目标是检查每个组件更改(当用户浏览页面时)是否已登录。如果没有-将他返回登录页面

编辑2 我是否可以将服务中的所有逻辑发布到
AuthGuard
文件中?它看起来像:

import {Injectable} from '@angular/core';
import {Router, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {UserAuthenticationService} from './UserAuthenticationService';
import {Http} from '@angular/http';

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

@Injectable()
export class WorksheetAccessGuard implements CanActivate {
    private static username: string;
    isUserAuthenticated: boolean = false;

    constructor(private router: Router, private userService: UserAuthenticationService, private http: Http) {
    }

    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

        this.http.get(`http://localhost/api/auth/isLogged/${this.username}`)
            .subscribe(res => {
                    this.isUserAuthenticated = res.json();
                },
                err => {
                    console.error('An error occured.' + err);
                });

        if (!this.isUserAuthenticated) {
            this.router.navigate(['/']);
            return false;
        }
        return true;
    }
}
从'@angular/core'导入{Injectable};
从'@angular/Router'导入{Router,RouterStateSnapshot,ActivatedRouteSnapshot};
从“rxjs/Observable”导入{Observable};
从“/UserAuthenticationService”导入{UserAuthenticationService};
从'@angular/Http'导入{Http};
接口激活{
canActivate(路由:ActivatedRouteSnapshot,状态:RouterStateSnashot):可观察的|承诺|布尔值
}
@可注射()
导出类工作表AccessGuard实现CanActivate{
私有静态用户名:字符串;
isUserAuthenticated:boolean=false;
构造函数(专用路由器:路由器,专用用户服务:UserAuthenticationService,专用http:http){
}
public canActivate(路由:ActivatedRouteSnapshot,状态:RouterStateSnashot):布尔值{
这是http.get(`http://localhost/api/auth/isLogged/${this.username}`)
.订阅(res=>{
this.isUserAuthenticated=res.json();
},
错误=>{
console.error('发生错误。'+err);
});
如果(!this.isUserAuthenticated){
this.router.navigate(['/']);
返回false;
}
返回true;
}
}

路由器状态快照
激活的路由快照
@angular/router
导入,而当前用户服务应该是您自己的,您应该在其中存储用户的已验证状态(例如布尔值)

您可以通过guard的构造函数中的依赖项注入来检索它的实例,如下所示:

import { CurrentUserService } from './path/to/your/service/file';
import { RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';

constructor(private userService: CurrentUserService) 
{}
您的服务需要在您的模块中提供(以及您的守卫),并且您需要在CurrentUserService中具有如下属性:

CurrentUserService

isAuthenticated: boolean = false;
import { CurrentUserService } from './path/to/your/service/file';

constructor(private userService: CurrentUserService) 
{}

login() {

... // Your existing code where you login on form submit or anything

this.userService.isAuthenticated = true;
}
这样,当您从登录组件(我假设您有一个)登录时,可以将服务属性设置为
true

登录组件

isAuthenticated: boolean = false;
import { CurrentUserService } from './path/to/your/service/file';

constructor(private userService: CurrentUserService) 
{}

login() {

... // Your existing code where you login on form submit or anything

this.userService.isAuthenticated = true;
}
编辑

isAuthenticated: boolean = false;
import { CurrentUserService } from './path/to/your/service/file';

constructor(private userService: CurrentUserService) 
{}

login() {

... // Your existing code where you login on form submit or anything

this.userService.isAuthenticated = true;
}
看看我的例子,它应该适合你的

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (!this.authService.isAuthenticated) {
        // Deny navigation and redirect to login
        this.router.navigate(['/path/to/login']);
        return false;
    }
    // Allow navigation (be careful that the guard always resolve a value)
    return true;
}

我不明白为什么要把它放在登录组件中?我已经在登录组件中实现了身份验证,但现在我想检查每个组件更改(用户在站点上导航)是否已登录。如果没有-返回登录页面。我已经做了一些服务,我会在几分钟后发布我的问题。基本上,这里的服务只用于共享您需要检查的属性,以了解您的用户是否已登录(在我的示例中,我使用了
isAuthenticated
)。因此,当用户登录时,
isAuthenticated
设置为
true
;您的警卫检查该值以返回
true
false
以允许导航或不允许导航。如果您没有要签入服务的属性,您的卫士就不能自己检查任何内容,如果您没有设置服务属性,您的卫士将始终返回
false
。如果卫士返回
false
,用户将无法在页面上导航?他只能留在登录组件中,是吗?在您的SparkBit示例中,代码直接检查存储在服务中的用户,而不是布尔属性。是的,导航将被允许,这取决于守卫的分辨率。我将编辑答案。完成。这是一个布尔值的基本示例,您可以自由地直接存储用户、他的权限或任何您自己的自定义身份验证保护。