Angular 正在向路由器添加动态路由,但不';行不通
我已经在angular 6中创建了一个应用程序,它在登录时将用户带到主页面。此页面包含顶部导航栏(称为Angular 正在向路由器添加动态路由,但不';行不通,angular,typescript,Angular,Typescript,我已经在angular 6中创建了一个应用程序,它在登录时将用户带到主页面。此页面包含顶部导航栏(称为工具栏)和左侧侧栏(称为侧导航)上的多个链接。我创建了一个定制的动态路由服务,可以为html模板添加链接及其标签 使用router.config.unshift将路径添加到路由器,我在控制台中记录路由器时已验证这些路径是否正确添加到config下 我的应用程序的登录页面有根路径(即'),登录后的Main页面有路径/Main(下面添加了路由器配置) 我似乎遇到的问题有两个部分: 每当我单击侧导航或
工具栏
)和左侧侧栏(称为侧导航
)上的多个链接。我创建了一个定制的动态路由服务,可以为html模板添加链接及其标签
使用router.config.unshift
将路径添加到路由器,我在控制台中记录路由器时已验证这些路径是否正确添加到config
下
我的应用程序的登录页面有根路径(即'
),登录后的Main
页面有路径/Main
(下面添加了路由器配置)
我似乎遇到的问题有两个部分:
侧导航
或工具栏
上的链接时,地址栏上的url会显示我localhost.com:4200/main/
,显示的页面是NotFoundComponent
(即它找不到路由)。我不希望路径是/main
的子项,而是根url(即'
),因为导航栏将位于每个页面上,这可能会在单击多个项目时出现类似localhost:4200/main///
的情况,这是一个非常糟糕的设计
localhost:4200/
,将显示相同的结果(NotFoundComponent
)。无论我做什么,它都找不到路径,即使在控制台中,当我记录路由器时,它是完全定义的DummyComponent
这是我的代码,我正在分享我的工具栏组件的代码
,侧导航几乎相同,除了一些位和块:
app.routing.ts:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from 'src/app/views/login/login.component';
import { MainComponent } from 'src/app/views/main/main.component';
import { AuthGuardService } from 'src/app/services/auth-guard/auth-guard.service';
import { NotFoundComponent } from 'src/app/views/error/not-found/not-found.component';
/**
* Contains a list of routes to enable navigation from one view to the next
* as users perform application tasks
* @property {array} routes
*/
export const routes: Routes = [
{
path: '',
component: LoginComponent,
},
{
path: 'main',
component: MainComponent,
canActivate: [AuthGuardService]
},
{
path: '**',
component: NotFoundComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
动态路由.service.ts
import { Injectable } from '@angular/core';
import { TranslatePipe } from 'src/app/pipes/translate/translate.pipe';
@Injectable({
providedIn: 'root'
})
/*
* This service will provide components with the ability to dynamically create
* routes within the application
*/
export class DynamicRoutingService {
/*
* Array for storing links
*
*/
private links = new Array<{ text: string, path: string, icon: string }>();
constructor(private translate: TranslatePipe) { }
/*
* Method to fetch data
*
*/
getLinks() {
if (this.links.length != 0) {
return this.links;
}
else {
throw new Error(this.translate.transform("generic[responses][error][404][002]"));
}
}
/*
* Method to store data
*
*/
addItem({ text, path, icon = null }) {
try {
this.links.push({ text: text, path: path, icon: icon });
} catch (e) {
throw new Error(this.translate.transform("generic[responses][error][400]"));
}
}
/*
* Method to remove a specific link
*
*/
removeItem({ text }) {
if (this.links.length != 0) {
this.links.forEach((link, index) => {
if (link.text === text) {
this.links.splice(index, 1);
}
});
} else {
throw new Error (this.translate.transform('generic[resposnes][error][404][002]'));
}
}
/*
* Remove all links from the array
*/
clearAll() {
this.links.length = 0;
}
}
import { Component, OnInit } from '@angular/core';
import { TranslatePipe } from 'src/app/pipes/translate/translate.pipe';
import { DynamicRoutingService } from 'src/app/services/dynamic-routing/dynamic-routing.service';
import { Router } from '@angular/router';
import { DummyComponent } from 'src/app/views/dummy/dummy.component';
@Component({
selector: 'app-toolbar',
templateUrl: './toolbar.component.html',
styleUrls: ['./toolbar.component.scss'],
providers: [DynamicRoutingService]
})
/**
* This component renders the Toolbar UI
*
*/
export class ToolbarComponent implements OnInit {
/**
* Object containing the translated names and their respective icons
* @property {array} links
*/
links: Array<{ text: string, path: string }>;
/**
* constructor for toolbar component is responsible for initializing translatePipe, dynamic routing and router,
* as well as adding routes dynamically to the router and the dynamicRouting service
* @param translate
* @param router
* @param dynamicRouting
*
*/
constructor(private translate: TranslatePipe, private router: Router, private dynamicRouting: DynamicRoutingService) {
this.router.config.unshift(
{ path: 'knowledge-base', component: DummyComponent },
{ path: 'home', component: DummyComponent },
{ path: 'settings', component: DummyComponent }
);
this.dynamicRouting.addItem({ text: "home", path: "home" });
this.dynamicRouting.addItem({ text: "knowledge_base", path: "knowledge-base" });
this.dynamicRouting.addItem({ text: "settings", path: "settings" });
}
/**
* Upon initialization this function fetches the links and inserts the translated
* text and path to be used by the template
*
* @param
* @return
*/
ngOnInit() {
this.links = [];
let rawData = this.dynamicRouting.getLinks();
let self = this;
rawData.forEach(function(data) {
let text = self.translate.transform("generic[toolbar][categories][" + data.text + "][label]");
self.links.push({ text: text, path: data.path });
});
}
}
从'@angular/core'导入{Injectable};
从'src/app/pipes/translate/translate.pipe'导入{translatepe};
@注射的({
providedIn:'根'
})
/*
*此服务将为组件提供动态创建
*应用程序中的路由
*/
导出类动态存储服务{
/*
*用于存储链接的数组
*
*/
私有链接=新数组();
构造函数(私有translate:translatepe){}
/*
*获取数据的方法
*
*/
getLinks(){
如果(this.links.length!=0){
返回此链接;
}
否则{
抛出新错误(this.translate.transform(“泛型[responses][Error][404][002]”);
}
}
/*
*方法来存储数据
*
*/
addItem({text,path,icon=null}){
试一试{
this.links.push({text:text,path:path,icon:icon});
}捕获(e){
抛出新错误(this.translate.transform(“泛型[responses][Error][400]”);
}
}
/*
*方法删除特定链接
*
*/
removeItem({text}){
如果(this.links.length!=0){
this.links.forEach((链接,索引)=>{
如果(link.text==文本){
本.链接.拼接(索引,1);
}
});
}否则{
抛出新错误(this.translate.transform('generic[resposnes][Error][404][002]);
}
}
/*
*从阵列中删除所有链接
*/
clearAll(){
this.links.length=0;
}
}
toolbar.component.ts
import { Injectable } from '@angular/core';
import { TranslatePipe } from 'src/app/pipes/translate/translate.pipe';
@Injectable({
providedIn: 'root'
})
/*
* This service will provide components with the ability to dynamically create
* routes within the application
*/
export class DynamicRoutingService {
/*
* Array for storing links
*
*/
private links = new Array<{ text: string, path: string, icon: string }>();
constructor(private translate: TranslatePipe) { }
/*
* Method to fetch data
*
*/
getLinks() {
if (this.links.length != 0) {
return this.links;
}
else {
throw new Error(this.translate.transform("generic[responses][error][404][002]"));
}
}
/*
* Method to store data
*
*/
addItem({ text, path, icon = null }) {
try {
this.links.push({ text: text, path: path, icon: icon });
} catch (e) {
throw new Error(this.translate.transform("generic[responses][error][400]"));
}
}
/*
* Method to remove a specific link
*
*/
removeItem({ text }) {
if (this.links.length != 0) {
this.links.forEach((link, index) => {
if (link.text === text) {
this.links.splice(index, 1);
}
});
} else {
throw new Error (this.translate.transform('generic[resposnes][error][404][002]'));
}
}
/*
* Remove all links from the array
*/
clearAll() {
this.links.length = 0;
}
}
import { Component, OnInit } from '@angular/core';
import { TranslatePipe } from 'src/app/pipes/translate/translate.pipe';
import { DynamicRoutingService } from 'src/app/services/dynamic-routing/dynamic-routing.service';
import { Router } from '@angular/router';
import { DummyComponent } from 'src/app/views/dummy/dummy.component';
@Component({
selector: 'app-toolbar',
templateUrl: './toolbar.component.html',
styleUrls: ['./toolbar.component.scss'],
providers: [DynamicRoutingService]
})
/**
* This component renders the Toolbar UI
*
*/
export class ToolbarComponent implements OnInit {
/**
* Object containing the translated names and their respective icons
* @property {array} links
*/
links: Array<{ text: string, path: string }>;
/**
* constructor for toolbar component is responsible for initializing translatePipe, dynamic routing and router,
* as well as adding routes dynamically to the router and the dynamicRouting service
* @param translate
* @param router
* @param dynamicRouting
*
*/
constructor(private translate: TranslatePipe, private router: Router, private dynamicRouting: DynamicRoutingService) {
this.router.config.unshift(
{ path: 'knowledge-base', component: DummyComponent },
{ path: 'home', component: DummyComponent },
{ path: 'settings', component: DummyComponent }
);
this.dynamicRouting.addItem({ text: "home", path: "home" });
this.dynamicRouting.addItem({ text: "knowledge_base", path: "knowledge-base" });
this.dynamicRouting.addItem({ text: "settings", path: "settings" });
}
/**
* Upon initialization this function fetches the links and inserts the translated
* text and path to be used by the template
*
* @param
* @return
*/
ngOnInit() {
this.links = [];
let rawData = this.dynamicRouting.getLinks();
let self = this;
rawData.forEach(function(data) {
let text = self.translate.transform("generic[toolbar][categories][" + data.text + "][label]");
self.links.push({ text: text, path: data.path });
});
}
}
从'@angular/core'导入{Component,OnInit};
从'src/app/pipes/translate/translate.pipe'导入{translatepe};
从'src/app/services/dynamic routing/dynamic routing.service'导入{DynamicRoutingService};
从'@angular/Router'导入{Router};
从'src/app/views/dummy/dummy.component'导入{DummyComponent};
@组成部分({
选择器:“应用程序工具栏”,
templateUrl:'./toolbar.component.html',
样式URL:['./toolbar.component.scss'],
提供者:[动态注册服务]
})
/**
*此组件呈现工具栏UI
*
*/
导出类ToolbarComponent实现OnInit{
/**
*对象,该对象包含已翻译的名称及其各自的图标
*@property{array}链接
*/
链接:数组;
/**
*工具栏组件的构造函数负责初始化TranslatePie、动态路由和路由器,
*以及向路由器和动态路由服务动态添加路由
*@param-translate
*@param路由器
*@param-dynameting
*
*/
构造函数(私有转换:translatePie,私有路由器:路由器,私有动态克隆:动态克隆服务){
this.router.config.unshift(
{path:'知识库',组件:DummyComponent},
{路径:'home',组件:DummyComponent},
{路径:'settings',组件:DummyComponent}
);
this.dynamicRouting.addItem({text:“home”,path:“home”});
this.dynamicRouting.addItem({文本:“知识库”,路径:“知识库”});
this.dynamicRouting.addItem({text:“settings”,path:“settings”});
}
/**
*初始化时,此函数获取链接并插入已翻译的
*模板要使用的文本和路径
*
*@param
*@返回
*/
恩戈尼尼特(){
this.links=[];
让rawData=this.dynamicCrouting.getLinks();
让自我=这个;
forEach(函数(数据){
让text=self.translate.transform(“通用[工具栏][类别][“+data.text+”][标签]”);
self.links.push({text:text,path:data.path});
});
}
}
toolbar.component.html
<app-header
[fixed]="true"
[navbarBrandFull]="{src: 'assets/logo.png', width: 143, height: 36, alt: 'RT Logo'}"
[navbarBrandMinimized]="{src: 'assets/logo2.png', width: 35, height: 35, alt: 'RT Logo'}"
[sidebarToggler]="'lg'">
<ul class="nav navbar-nav d-md-down-none" routerLinkActive="active">
<li class="nav-item px-3" *ngFor="let link of links">
<a class="nav-link" [routerLink]="link.path">{{ link.text }}</a>
</li>
</ul>
<ul class="nav navbar-nav ml-auto">
</ul>
</app-header>
-
{{link.text}
已解决:问题出在我的模板中:传递给routerLink
的值需要修改,请提供一个