EXCEPTION:未捕获(承诺):错误:无法匹配任何路由。网址细分:'详细信息'

时间:2017-01-30 21:48:22

标签: angular typescript routing components router

我有这个路由器:

import { Route, RouterModule } from '@angular/router';
import { ProjectDetailsComponent } from '../components/project-details/project-details.component';

export const ROUTES: Route[] = [
  {
    path: '',
    redirectTo: '/details',
    pathMatch: 'full'
  },
  {
    path: 'details/:id',
    component: ProjectDetailsComponent
  }
];

我还有一个名为ProjectDetailsComponent的适当控制器。

这是我的app模块,我在其中注册了我的路线:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';

// Custom components
import { AppComponent } from './app.component';
import { ProjectDetailsComponent } from './components/project-details/project-details.component';

// Routes
import { ROUTES } from './services/router';

@NgModule({
  imports: [
    BrowserModule,
    RouterModule.forRoot(ROUTES, { useHash: true })
  ],
  declarations: [AppComponent, ProjectDetailsComponent],
  bootstrap: [AppComponent]
})
export class AppModule {
}

它是我的app.component,我尝试使用" / details"重定向到ProjectDetailsComponent。路线并发送给它项目ID:

import { Component, OnInit } from '@angular/core';
import { IProject } from './domain/projects
import { Router } from '@angular/router';
// Routes
import { ROUTES } from './services/router';

@Component({
    selector: 'projects-app',
    templateUrl: 'app/app.component.html'
})
export class AppComponent implements AfterViewInit {
    public activeProject: IProject;
    public projects: Array<IProject>;

    constructor(public router: Router) {
    }

    ngOnInit() {
        this.router.navigate(['/details', this.activeProject.Id]);
    }
}

但是当我尝试导航到&#39; details /:id&#39;路由器我得到以下错误:

C:\Sources\SolarPro\build\debug\resources\app\node_modules\@angular\core\bundles\core.umd.js:3521 EXCEPTION: Uncaught (in promise): 
   Error: Cannot match any routes. URL Segment: 'details'

请帮我解决我的问题。

2 个答案:

答案 0 :(得分:2)

重定向将转到/details,但没有定义组件。您需要为/details定义组件。

routes.ts

export const ROUTES: Routes = [
  {
    path: '',
    redirectTo: '/details',
    pathMatch: 'full'
  },
  {
    path: 'details',
    component: DetailsComponent
  },
  {
    path: 'details/:id',
    component: ProjectDetailsComponent
  }
];

details.component.ts

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.css']
})
export class DetailsComponent implements OnInit {

  constructor(private router: Router) { }

  ngOnInit() {
    this.router.navigate(['/details', 1]);
  }

}

答案 1 :(得分:0)

我面临同样的问题申请,所有可能的解决方案,但最后,这解决了我的问题

export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['details']); // or redirect to default route
    }
  }
}

这将起作用,因为角度4没有给出任何默认路由,因此处理错误捕获并且您可以重定向到默认路由