Ошибка: Uncaught (в обещании): Ошибка: не удается сопоставить ни один маршрут.Сегмент URL: 'edit / 2' - PullRequest
0 голосов
/ 25 апреля 2018

У меня есть простое приложение, работающее с angular4, но я получил следующую ошибку:

 :1440 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'edit/2'
Error: Cannot match any routes. URL Segment: 'edit/2'
    at ApplyRedirects.noMatchError (router.js:1719)
    at CatchSubscriber.eval [as selector] (router.js:1684)
    at CatchSubscriber.error (catchError.js:105)
    at MapSubscriber.Subscriber._error (Subscriber.js:131)

Это структура проекта:

--src
    --app
        --views
            --admin
                --GestionProjects
                     --projects
                           --edit-projects
                                 --edit-project.component.ts
                                 --edit-project.component.html
                           --projects.component.ts
                           --projects.component.html
                     --new-project
                           --new-project.component.ts
                           --new-project.component.html
                     --project.module.ts
                     --project-routing.module.ts

это файловое приложение.routing.ts

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

// Import Containers
import {
  FullLayoutComponent,
  SimpleLayoutComponent
} from './containers';

export const routes: Routes = [
  {
    path: '',
    redirectTo: 'pages',
    pathMatch: 'full',
  },
  {
    path: '',
    component: FullLayoutComponent,
    data: {
      title: 'Home'
    },
    children: [

      {
        path: 'GestionProject',
        loadChildren: './views/Admin/GestionProjects/projet.module#ProjetModule'
      } 

    ]
  },
  {
    path: 'pages',
    component: SimpleLayoutComponent,
    data: {
      title: 'Pages'
    },
    children: [
      {
        path: '',
        loadChildren: './views/pages/pages.module#PagesModule',
      }
    ]
  }
];

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

файл project-routing.module.ts:

    import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {ProjectsComponent} from './projects/projects.component';
import {NewProjectsComponent} from './new-projects/new-projects.component';
import {EditProjectComponent} from './projects/edit-project/edit-project.component';


const routes: Routes = [
  {
    path: '',
    data: {
      title: 'Projects'
    },
    children: [
      {
        path: 'list',
        component: ProjectsComponent,
        data: {
          title: 'List of projects'
        },
        children: [
          {
            path: 'edit/:id',
            component : EditProjectComponent,
            data : {
              title: 'editer a project'
            }
          }
        ]
      },
      {
        path: 'add',
        component : NewProjectsComponent,
        data: {
          title: 'add a new project'
        }
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})

export class ProjetRoutingModule {}

файл project.component.ts

    import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import {ProjetService} from '../../../../../service/projet.service';
import {Projet} from '../../Models/Projet';
import 'rxjs/add/operator/map';

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

  pageProjects:any;
  pages:Array<number>;

  constructor(private router:Router,
              private projetSevice:ProjetService ) { }

  ngOnInit() {

        this.projetSevice.getProjects()
          .subscribe(data=>{
            this.pageProjects=data;
          },err=>{
            console.log('this is error');
          })
  }

  Edit(id:number){
    this.router.navigate(['edit',id]);
  }

  delete(p:Projet){
      let confirm = window.confirm('are you sur .. ');
      if(confirm==true){
        this.projetSevice.deleteProject(p.id)
          .subscribe(data=>{
            this.pageProjects.splice(
              this.pageProjects.indexOf(p),1
            );
          },err=>{
            console.log(err);
          })
      }
  }

}

и finnalyфайл project.component.html

<table class="table table-striped">
        <thead>
        <tr>
          <th>Numéro</th>
          <th>Intitulé</th>
          <th>Description</th>
          <th></th>
        </tr>
        </thead>
        <tbody>

        <tr *ngFor="let c of pageProjects">
          <td>{{c.id}}</td>
          <td>{{c.intitule}}</td>
          <td>{{c.description}}</td>
          <td><a (click)="delete(c)">delete</a> <a (click)="Edit(c.id)">Edit</a></td>
        </tr>

        </tbody>
      </table>

у меня есть еще один файл с именем _nav.ts:

 export const navigation = [
  {
    name: 'Tableau de bord',
    url: '/dashboard',
    icon: 'icon-speedometer',
  },
{
    name: 'Projets',
    url: '/GestionProjects',
    icon: 'icon-puzzle',
    children: [
      {
        name: 'List of projects',
        url: '/list',
        icon: 'icon-puzzle'
      },
      {
        name: 'add a new project',
        url: '/add',
        icon: 'icon-puzzle'
      }

    ]
  },
}

, который я вызываю в файле с боковой панелью навигации:

enter image description here

все идет хорошо, получая список проектов, которые я хочу, но когда я нажимаю на редактирование, я получаю ошибку выше rror: Невозможно сопоставить ни один маршрут ...

помогите пожалуйста :)

1 Ответ

0 голосов
/ 26 апреля 2018

Вы пытались перейти к абсолютному URL, который приведет вас к

  localhost/#/edit/2 // which not found

вам придется использовать относительную навигацию к текущему маршруту

constructor(private router: Router, private route: ActivatedRoute) {}

this.router.navigate(['edit',id], { relativeTo: this.route });
...