首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >添加到路由器的动态路由,但不工作

添加到路由器的动态路由,但不工作
EN

Stack Overflow用户
提问于 2019-03-04 11:15:12
回答 1查看 508关注 0票数 2

我在Range6中创建了一个应用程序,它在登录时将用户带到主页。此页面包含顶部的导航条(称为toolbar)和左侧的侧栏(称为side-nav)上的多个链接。我已经创建了一个定制的动态路由服务,它将为html模板添加链接及其标签。

使用router.config.unshift将这些路径添加到路由器,并且我已经验证,当我在控制台中记录路由器时,这些路径是在config下正确添加的。

我的应用程序的登录页面有根路径(即' '),登录后的Main页面有路径/main (下面添加的路由器配置)。

我似乎遇到的问题有两部分:

  1. 每当我单击side-navtoolbar上的链接时,地址栏上的url显示localhost.com:4200/main/<path>,显示的页面是NotFoundComponent (即无法找到路由)。我不希望路径是child of /main,而是根url (即' '),因为导航栏将出现在每个页面上,这可能会在单击多个条目时出现类似localhost:4200/main/<path>/<anotherpath>/<someotherpath>/<path>的情况,这是一个相当的糟糕设计。
  2. 如果我尝试手动添加路径到应用程序,例如。localhost:4200/<path>显示了相同的结果(NotFoundComponent)。不管我做什么,它根本找不到路径,即使在控制台中,当我记录路由器时,它是完全定义的。

出于测试目的,我的所有路径都将我重定向到DummyComponent

下面是我的代码,我正在为我的ToolbarComponent共享代码,除了一些零碎代码外,Nav的代码几乎是一样的:

app.routing.ts

代码语言:javascript
复制
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 { }

dynamic-routing.service.ts

代码语言:javascript
复制
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;
  }
}

toolbar.component.ts

代码语言:javascript
复制
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 });
    });
  }

}

toolbar.component.html

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-14 05:02:48

解决了:问题就在我的模板中:传递给routerLink的值需要修改,example heresolution here

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54982101

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档