Sas*_*ota 7 javascript url-routing typescript angular-ui-router angular
我通过设置路由配置@NgModule.我有一项服务,根据特定条件确定应该为用户显示应用程序的哪些部分.我需要调用该服务并根据返回的值设置路由.
问题:路径配置是在注释中设置的,我无法在这样的设置中获得如何调用服务.
这里更具体的是我想要增强的示例配置.
我目前的路由设置:
const appRoutes: Routes = [
{
path: '',
redirectTo: 'first-route',
pathMatch: 'full'
},
{
path: 'first-route',
component: FirstComponent,
pathMatch: 'full'
},
{
path: 'second-route',
component: SecondComponent,
pathMatch: 'full'
},
...
];
@NgModule({
imports: [RouterModule.forChild(appRoutes)],
exports: [RouterModule]
})
export class MyRoutingModule {
}
Run Code Online (Sandbox Code Playgroud)
应该更改路由设置的服务:
@Injectable()
export class MyService {
getAccessibleRoutes(): Observable<string[]> {...}
}
Run Code Online (Sandbox Code Playgroud)
问题:如何拨打服务电话并更改路线?
注意:我还查看了"动态添加Angular中的路由"和"我们如何动态地将新路由添加到RouterModule(@NgModule导入)",但我还没有找到明确的答案.
小智 5
如果我正确理解了您的问题,我想您可能可以考虑使用路线守卫来达到您的目标。我建议您使用守卫功能来指定访问您的路线的条件,而不是更改路线列表。
有关路线守卫的更多信息,请查看此链接:
https://codecraft.tv/courses/angular/routing/router-guards/
我希望这能帮到您。
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { YourSecurityService } from './your-security.service';
@Injectable()
export class YourRouteGuardService implements CanActivate {
constructor(
private router: Router,
private yourSecurityService: YourSecurityService) {
}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
console.log(state.url); // HERE YOU CAN GET REQUESTED ROUTE
if (this.yourSecurityService.checkIfUserHaveAccess())
return true;
this.router.navigate(['your-route-to-redirect']);
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
接下来,您应该将您的守卫应用于您的路线:
const appRoutes: Routes = [
{
path: 'someroute',
component: RouteComponent,
canActivate: [YourRouteGuardService]
},
...
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1866 次 |
| 最近记录: |