angular - 动态路由被添加到路由器但不起作用
问题描述
我在 Angular 6 中创建了一个应用程序,登录后将用户带到主页。toolbar
此页面在顶部的导航栏(称为)和左侧的侧栏(称为 )上包含多个链接side-nav
。我创建了一个自定义动态路由服务,它将为 html 模板添加链接及其标签。
使用 将路径添加到路由器,并且当我在控制台中登录路由器时router.config.unshift
,我已验证这些路径已正确添加。config
我的应用程序的登录页面有根路径(即' '
),Main
登录后的页面有路径/main
(下面添加了路由器配置)。
我似乎遇到的问题有两个部分:
每当我单击
side-nav
或 上toolbar
的链接时,地址栏上的 url 都会显示给我localhost.com:4200/main/<path>
,而显示的页面是NotFoundComponent
(即找不到路线)。我不希望路径是child
根/main
url (ie' '
),因为导航栏会在每个页面上,这可能会导致localhost:4200/main/<path>/<anotherpath>/<someotherpath>/<path>
单击多个项目的情况,这是一个非常糟糕的设计。如果我尝试手动添加应用程序的路径,例如。
localhost:4200/<path>
显示相同的结果(NotFoundComponent
)。无论我做什么,它都找不到路径,即使在控制台中它在我登录路由器时已经完美定义。
出于测试目的,我的所有路径都将我重定向到DummyComponent
.
这是我的代码,我正在分享我的代码,ToolbarComponent
除了一些点点滴滴,Side Nav 几乎相同:
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;
}
}
工具栏.component.ts
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 });
});
}
}
工具栏.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>
解决方案
推荐阅读
- django - Django admin,如何在查看和编辑期间隐藏特定模型字段
- amazon-web-services - AWS Cloudformation 输出 ElastiCacheCluster
- android - 底部导航的导航组件总是创建新的片段
- laravel - Illuminate \ Database \ QueryException (42P01) SQLSTATE[42P01]: Undefined table: 7 ERROR: relationship "suggesteds" does not exist LINE 1
- python - 尝试使用 Arduino 时出现 Python TypeError
- awk - for 循环不会遍历 csv 验证器中的每一行
- php - 两种 PHP 缓存技术
- powershell - 将对象属性添加到 Powershell 中的另一个对象
- ios - MFMailComposeViewController 布局错误
- parameters - Wiremock 单个查询参数的多重匹配