我正在使用Angular 4,并且尝试使用一些外部数据动态设置路由。
基于Internet提供的一些解决方案,我试图通过调用来动态加载路由:
this.router.config.unshift({path:'base',component:BaseComponent,data:this.rcs.getRouteData('base')});
这里的rcs
只是一种服务-(提供者)一些数据,这些数据将传递给在此路径上被调用的组件。
但是,如果我尝试从其他组件动态设置相同的路由路径(即通过从AppComponent(app.component.ts)之外的其他组件调用router->config->unshift
方法),则路由无效。在这种情况下,如果我尝试路由到动态设置的路径,它将带回到设置为"**"
的组件(基本上是返回到找不到匹配路径配置时应显示的组件)。>
我是否在这里缺少任何东西,我如何从AppComponent以外的任何其他组件动态加载角度路径。
代码: app.component.ts:
import {Component} from '@angular/core';
import{DataService} from './services/data.service';
import {Item} from './components/item/item';
import {BaseComponent}from './components/base/base.component';
import {ItemData} from './components/item/item-data';
import {ProcessContextService} from './services/context/process-context.service';
import {RouteCfgService} from './services/routing/route-cfg.service';
import {Router} from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss'],
})
export class AppComponent {
public constructor(private pcs:ProcessContextService,private dataservice:DataService, private router:Router,private rcs: RouteCfgService){
this.rcs.setRoutes();
alert("datatosetis ROOTC CONTROLLER:"+JSON.stringify(this.rcs.getRouteData('base')));
this.router.config.unshift({path:'base',component:BaseComponent,data:this.rcs.getRouteData('base')});
console.log("THE ROUTER CONFIG IS:");
console.log(this.router.config);
}
}
app.component.html
<router-outlet></router-outlet>
路由模块
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {PageNotFoundComponent} from '../../components/page-not-found/page-not-found.component';
import {RootcComponent}from '../../components/rootc/rootc.component';
import {IdeComponent}from '../../components/architect/ide/ide.component'
import { MngOrgComponent } from '../../components/architect/mng-org/mng-org.component';
import {BaseComponent}from '../../components/base/base.component';
import { DataStoreViewComponent } from '../../components/architect/data-store-view/data-store-view.component';
const routes: Routes = [
{
path:'login',
component:RootcComponent
}, {
path:'ide',
component:IdeComponent,
children:[
{
path: 'setuporg',
component: MngOrgComponent,
outlet: 'ideolet'
}, {
path: 'datastoreview',
component: DataStoreViewComponent,
// outlet: 'ideolet'
},
// {
// path: 'basecomponent',
// component: BaseComponent,
// // outlet: 'ideolet'
// }
]
},
{
path: '',
redirectTo:'/login',
pathMatch:'full'
},
{
path: '**',
component:PageNotFoundComponent,
pathMatch:'full'
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class ApprouteRoutingModule { }