我在我的角度项目中使用了Route Guard,并且在我的角度项目中实现了Service组件的路线保护。现在我遇到一个错误,该错误将在Visual Studio编辑器中显示为->找不到名称“ next”。
当我尝试在angular项目的auth.guard.ts中使用next关键字时显示错误。
在auth.guard.ts中
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, CanActivate } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
user = {
role: 'ADMIN'
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
if(user.data[0] == this.user.role)
return true;
throw new Error("Method not implemented.");
}
}
在app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutusComponent } from './aboutus/aboutus.component';
import { ServicesComponent } from './services/services.component';
import { AuthGuard } from './guards/auth.guard';
const routes: Routes = [
{
path:'',
component:HomeComponent
},
{
path:'aboutus',
component:AboutusComponent
},
{
path:'services',
component:ServicesComponent,
canActivate: [AuthGuard],
data: ['ADMIN']
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
在app.module.ts
中import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { HomeComponent } from './home/home.component';
import { AboutusComponent } from './aboutus/aboutus.component';
import { ServicesComponent } from './services/services.component';
import { AuthGuard } from './guards/auth.guard';
@NgModule({
declarations: [
AppComponent,
NavbarComponent,
HomeComponent,
AboutusComponent,
ServicesComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
答案 0 :(得分:0)
接下来按路线替换,因为您的数据应从ActivatedRouteSnapshot(在您的示例中作为路线)获取。
答案 1 :(得分:0)
正在搜索的下一个在您的构造方法中声明为“ 路线”。这将为您工作:
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, CanActivate } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
user = {
role: 'ADMIN'
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
if(route.data[0] == this.user.role){
return true;
}
return false;
}
}