我正在研究Angular 6应用程序。我有从数据库加载动态路由的要求。为此,我要注入路由服务类(DynamicRoutingService),该类负责从数据库加载静态和动态路由,并添加app.module.ts-> RouterModule.forRoot(RouteCollection)。
在DynamicRoutingService类中,我正在使用Subscribe方法加载数据,我的问题是请求的URL页面在Subscribe方法获得http结果之前就已呈现,因此,应用程序抛出无效路由错误。
我碰巧使用决心并承诺解决此问题,但不确定我是否确实做到这一点,那是我需要帮助的地方
local-infile
Injectable()
export class AppRoutingResolver implements Resolve<any>{
constructor(
private router: Router
){}
resolve(route: ActivatedRouteSnapshot):Promise<any> | boolean{
return false;
}
}
export class AppComponent {
constructor(private routingService:DynamicRoutingService){
routingService.initializeDynamicRoutes(); // call service to reload routes
}
}
@NgModule({
imports: [
RouterModule.forRoot(RouteCollection)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {
constructor(
private router:Router
) {
}
}
@Injectable({
providedIn: 'root'
})
export class DynamicRoutingService {
private dynamicRoutes: Route[] = [];
private waitToLoadRoutes: boolean = true;
private dynamicRoutesData: any;
private routeObject: any;
routeSubject: string = "survey";
static forEach: any;
constructor(
private router: Router,
private dynamicRoutesDataServices: DynamicRoutesDataServices
) { }
public initializeDynamicRoutes() {
this.loadDynamicRoutes();
}
public loadDynamicRoutes(): Route[] {
//LOADING DATA FROM DATABASE
this.dynamicRoutesDataServices.GetDynamicRoutesCollection(this.routeSubject)
.subscribe((result: any) => {
if (result) {
this.dynamicRoutesData = result
if (this.dynamicRoutesData) {
this.assembleDynamicRoutes();
}
}
});
return this.dynamicRoutes;
}
export class DynamicRoutesDataServices{
constructor(
private getDynamicRoutesQuery:GetDynamicRoutesQuery
){}
public GetDynamicRoutesCollection(routesSubject: string): any{
this.getDynamicRoutesQuery.initialise(routesSubject);
var result = this.getDynamicRoutesQuery.execute();
return result;
}
}
答案 0 :(得分:2)
我不确定您是否在这里使用正确的方法来加载动态路由。角解析器是为指定路由预取数据的助手。
示例1:
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamComponent,
resolve: {
team: TeamResolver
}
}
])
解析器将团队的信息存储在ActivatedRoute数据属性的team属性中。因此,您需要将其附加到现有路由。
https://angular.io/api/router/Resolve
https://codeburst.io/understanding-resolvers-in-angular-736e9db71267