【发布时间】:2021-08-09 04:38:24
【问题描述】:
我正在尝试创建一个 Guard 服务来验证我的路由。但我的守卫服务位于共享库中。
这是我的警卫服务:
@Injectable({
providedIn: 'root'
})
export class RouteGuard implements CanActivate {
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
return true;
}
}
在共享模块中提供:
import {RouteGuard} from './auth/guard/route.guard';
@NgModule({
imports: [CommonModule, MaterialModule],
exports: [MaterialModule],
providers: [RouteGuard]
})
export class SharedModule {}
现在我需要在 app 模块中获得这项提供的服务。我该怎么做?
import {SharedModule} from '@acn-collections-ws/shared';
@NgModule({
declarations: [AppComponent, AuthComponent, LoggedComponent, HomeComponent, LoginComponent, SigninComponent],
imports: [BrowserModule, BrowserAnimationsModule, AppRoutingModule, SharedModule],
providers: [],
bootstrap: [AppComponent],
exports: [
AuthComponent,
LoggedComponent,
HomeComponent,
LoginComponent,
SigninComponent
],
})
export class AppModule {}
我需要在我的应用路由模块中导入此服务,并与 canActivate 路由验证器一起使用。像这样:
// i cant found RouteGuard at acn-collections-ws/shared
import { RouteGuard } from '@acn-collections-ws/shared';
const routes: Routes = [
{
path: '',
component: LoggedComponent,
children: [
{path: '', component: HomeComponent}
],
canActivate: [RouteGuard]
},
{
path: '',
component: AuthComponent,
children: [
{path: '', redirectTo: 'login', pathMatch: 'full'},
{path: 'login', component: LoginComponent},
{path: 'signin', component: SigninComponent}
]
}
];
【问题讨论】:
-
你为什么在
'@acn-collections-ws/shared'中寻找RouteGuard?不是来自'some_way/auth/guard/route.guard'吗? -
我的守卫位于共享库
@acn-collections-ws/shared -
我正在使用 @nwrl 库 --preset=angular。有了这个,我可以使用@ 导入外部库
-
你能创建一个最小的可验证stackblitz 示例吗?
-
我今天以后会尝试这样做。谢谢兄弟!
标签: javascript angular angular-ui-router ng-modules