Angular:根据服务方法调用设置路由 [英] Angular: Setup routes depending on service method call
问题描述
我通过 @NgModule
设置了路由配置.我有一项服务,可以根据特定条件确定应向用户显示应用程序的哪些部分.我需要调用该服务并根据返回值设置路由.
I have route configuration set up via @NgModule
. And I have a service that identifies what parts of the application should be shown for the user depending on certain conditions. I need to call that service and setup the routes according to the returned value.
问题:路由配置是在注释中设置的,我无法在这样的设置中调用服务.
Problem: Route configuration is setup inside an annotation and I can't get how to call the service in such setup.
更具体地说,这里是我想要增强的示例配置.
To be more specific here is the example configuration I want to enhance.
我当前的路由设置:
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 {
}
应该改变路由设置的服务:
The service that should change the route setup:
@Injectable()
export class MyService {
getAccessibleRoutes(): Observable<string[]> {...}
}
问题:如何拨打服务电话并更改路线?
Question: How can I make a service call and change the routes?
注意:我还查看了在 Angular 中动态添加路由" 和 "我们如何将新路由动态添加到 RouterModule(@NgModule 导入)" 但我没有在那里找到了明确的答案.
Note: I also looked on "Dynamically adding routes in Angular" and "How we can add new routes dynamically into RouterModule(@NgModule imports)" but I haven't found clear answer there.
推荐答案
如果我正确理解了你的问题,我想你可能可以考虑使用路由守卫来达到你的目标.建议您使用guards功能来指定访问路由的条件,而不是更改路由列表.
If I correctly understood your problem, I think you probably can consider using route guards to reach you goal. I suggest you to use guards feature to specify the conditions of accessing your routes, instead of changing the list of routes.
有关路线守卫的更多信息,请查看此链接:
Please check this link for more information about route guards:
https://codecraft.tv/courses/angular/routing/router-守卫/
希望对你有所帮助.
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;
}
}
接下来你应该在你的路线上应用你的守卫:
Next you should apply your guard to your route:
const appRoutes: Routes = [
{
path: 'someroute',
component: RouteComponent,
canActivate: [YourRouteGuardService]
},
...
]
这篇关于Angular:根据服务方法调用设置路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!