错误错误:未捕获(承诺):错误:无法匹配任何路由。网址段:“主要/基于知识库”

时间:2019-01-01 08:25:51

标签: angular typescript

我正在用角度6为我的应用程序设置动态路由,并且在运行该应用程序时没有编译错误,但是一旦单击链接(例如知识库),它就会给我以下错误: / p>

core.js:1673错误错误:未被捕获(承诺):错误:无法匹配任何路由。网址段:“主要/基于知识库”

我遵循了HereHere的教程,将动态路由应用到我的应用程序,这将允许components创建链接,在屏幕上显示它们并在单击时重定向。为了进行测试,我创建了一个dummyComponent,最初将在每条路由中使用,但是在工作时将由实际的components代替。

但是,由于上述错误,我无法使用此工具。我尝试浏览当前的解决方案,最相关的是thisthis,但是它们并不能真正解决我遇到的问题。我可能想念什么吗?

这是我的代码:

toolbar.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]
})

/**
* The purpose of this file is to provide the html template with the translated names
* for the categories in the toolbar.
*/
export class ToolbarComponent implements OnInit {

/**
* Object containing the translated names and their respective icons
* @property {array} links
*/
links: Array<{ text: string, path: string }>;

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" });
}

  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

<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>

dynamic-routing.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
/*
* This service will provide components with the ability to dynamically create
* routes within the application
*/
export class DynamicRoutingService {

  /*
  *
  * @property {array} links
  */
  private links = new Array<{ text: string, path: string, icon: string }>();

  constructor() { }

  /*
  * Method to fetch data
  *
  */
  getLinks() {
    return this.links;
  }

  /*
  * Method to store data
  * @param text, path, icon
  */
  addItem({ text, path, icon = null }) {
    this.links.push({ text: text, path: path, icon: icon });
  }

  /*
  * Method to remove a specific link0
  * @param text
  */
  removeItem({ text }) {
    this.links.forEach((link, index) => {
      if (link.text === text) {
        this.links.splice(index, 1);
      }
    });
  }

  /*
  * Remove all links from the array
  */
  clearAll() {
    this.links.length = 0;
  }
}

app.routing.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';


import { LoginComponent } from './views/login/login.component';
import { MainComponent } from './views/main/main.component';
import { AuthGuardService } from './services/auth-guard/auth-guard.service';

export const routes: Routes = [
  {
    path: '',
    component: LoginComponent,

  },
  { path: 'main',
    component: MainComponent,
    canActivate: [AuthGuardService]
  }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

预期:链接应正确重定向到路由,例如“主要/名称”

实际

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'main/home'
Error: Cannot match any routes. URL Segment: 'main/home'
    at ApplyRedirects.push../node_modules/@angular/router/fesm5/router.js.ApplyRedirects.noMatchError (router.js:1384)
    at CatchSubscriber.selector (router.js:1365)
    at CatchSubscriber.push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (catchError.js:34)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:80)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:80)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:80)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (tap.js:61)
    at ApplyRedirects.push../node_modules/@angular/router/fesm5/router.js.ApplyRedirects.noMatchError (router.js:1384)
    at CatchSubscriber.selector (router.js:1365)
    at CatchSubscriber.push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (catchError.js:34)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:80)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:80)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:80)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (tap.js:61)
    at resolvePromise (zone.js:814)
    at resolvePromise (zone.js:771)
    at zone.js:873
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:3811)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
    at drainMicroTaskQueue (zone.js:595)
    at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:500)
    at invokeTask (zone.js:1540)
defaultErrorLogger @ core.js:1673
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:1719
next @ core.js:4311
schedulerFn @ core.js:3551
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:196
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:134
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:77
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:54
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3535
(anonymous) @ core.js:3842
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138
push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js:3779
onHandleError @ core.js:3842
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.handleError @ zone.js:392
push../node_modules/zone.js/dist/zone.js.Zone.runGuarded @ zone.js:154
_loop_1 @ zone.js:677
api.microtaskDrainDone @ zone.js:686
drainMicroTaskQueue @ zone.js:602
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:500
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566

1 个答案:

答案 0 :(得分:1)

您没有为/main定义任何子路由路径。这就是您收到该错误的原因。从您编写的内容来看,您只能路由到/main。添加以下内容:

您可以将其他路径直接注册为main/:somePath,也可以将子路由添加到/main

方法1

export const routes: Routes = [
  { path: 'main',
    component: MainComponent,
    canActivate: [AuthGuardService],
    pathMatch : 'full'
  },
  { path: 'main/:somePath',
    component: MainComponent
  },
  {
    path: '',
    component: AppComponent,
  }
];

方法2:

export const routes: Routes = [
  { path: 'main',
    children :[
       {path: ':somePath', component: MainComponent}
    ],
    component: SomeComponent
  },
  {
    path: '',
    component: AppComponent,
  },
];

注意:始终在末尾添加空的路由路径。这样它就可以首先匹配更具体的路由。否则,您将不得不使用pathMatch:'full'