Несколько маршрутов в Angular 2+ - PullRequest
0 голосов
/ 22 января 2019

Я пытался сделать эту работу, и я провел много исследований, но я не могу найти ответ. Я создаю приложение с несколькими маршрутами розетки в угловых 2 +.

У меня есть это:

App.Component.html

<div>
<div>
<nav mat-tab-nav-bar>
  <a mat-tab-link
     *ngFor="let link of navLinks"
     [routerLink]="{ outlets: {form: link.path } }"
     routerLinkActive="active-link" #rla="routerLinkActive"
     [active]="rla.isActive">
    <span><mat-icon>{{link.icon}}</mat-icon></span>
    <span>{{link.label}}</span>
  </a>
</nav>
    <router-outlet name="form"></router-outlet>
</div>
</div>




 <router-outlet></router-outlet>

app.module.ts

const appRoutes: Routes = [
  { path: 'home', component: HomeComponent,
    children: [
      { path: "hotel",  component: HotelSearchFormApiComponent, outlet:"form"},
      { path: "groups", component: GroupRequestFormComponent, outlet:"form"},
      { path: "flight", component: flightsSearchFormComponent, outlet:"form"},
      { path: "", component: HomeComponent},
      //{ path: "", redirectTo: "hotel", pathMatch: "full" },
      { path: "**", redirectTo: "hotel" },
    ]
   },
  { path: 'hotel/rate',      component:  RatesComponent },
  { path: 'hotel/:countryCod/:stateCod/:cityCod/:dateFrom/:dateTo',      component:  SearchHotelResultComponent },

App.component.ts

navLinks = [
{
    path:'./home/hotel',
    icon: 'hotel',
    label:   'Hoteles'
},
{
    path:'/home/flight',
    icon:'flight',
    label: 'Vuelos'
}
,
{
    path:'./home/Package',
    icon:'work',
    label: 'Paquetes'
}
,
{
    path:'./home/groups',
    icon:'group',
    label: 'Grupos'
}
]

Но когда я нажимаю на кнопку, я получаю эту проблему:

error: Error: Cannot match any routes. URL Segment: '/home/flight' at ApplyRedirects.push.../../node_modules/@angular/router/fesm5/router.js.ApplyRedirects.noMatchError (http://localhost/a/vendor.js:140670:16) at CatchSubscriber.selector (http://localhost/a/vendor.js:140651:29) at CatchSubscriber.push.../../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (http://localhost/a/vendor.js:181982:31) at MapSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (http://localhost/a/vendor.js:178721:26) at MapSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (http://localhost/a/vendor.js:178701:18) at MapSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (http://localhost/a/vendor.js:178721:26) at MapSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (http://localhost/a/vendor.js:178701:18) at MapSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (http://localhost/a/vendor.js:178721:26) at MapSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (http://localhost/a/vendor.js:178701:18) at TapSubscriber.push.../../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (http://localhost/a/vendor.js:186715:26)
message: "Cannot match any routes. URL Segment: '/home/flight'"
stack: "Error: Cannot match any routes. URL Segment: '/home/flight'↵    at ApplyRedirects.push.../../node_modules/@angular/router/fesm5/router.js.ApplyRedirects.noMatchError (http://localhost/a/vendor.js:140670:16)↵    at CatchSubscriber.selector (http://localhost/a/vendor.js:140651:29)↵    at CatchSubscriber.push.../../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (http://localhost/a/vendor.js:181982:31)↵    at MapSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (http://localhost/a/vendor.js:178721:26)↵    at MapSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (http://localhost/a/vendor.js:178701:18)↵    at MapSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (http://localhost/a/vendor.js:178721:26)↵    at MapSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (http://localhost/a/vendor.js:178701:18)↵    at MapSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (http://localhost/a/vendor.js:178721:26)↵    at MapSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (http://localhost/a/vendor.js:178701:18)↵    at TapSubscriber.push.../../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (http://localhost/a/vendor.js:186715:26)"
__proto__: Object
id: 3
url: "/home(form:/home/flight)"

Кроме того, / Home не перенаправляет на дом / отель.

Раньше у меня была одна розетка, и я работал безупречно: (.

Заранее спасибо.

Андрес

Ответы [ 2 ]

0 голосов
/ 22 января 2019

Похоже, вы не инициализировали переменную appRoutes. Вам необходимо добавить его в блок импорта модуля App.

     import { RouterModule } from '@angular/router';
     @NgModule({
        ...
            imports: [
                ...
                RouterModule.forRoot(appRoutes)
            ],
        ...
        })
       export class AppModule{}
0 голосов
/ 22 января 2019

Проблема, с которой вы столкнулись, заключается в том, что вы пытаетесь перейти к несуществующему маршруту.Позвольте мне объяснить здесь более подробно, у вас есть маршрут под названием home. Допустим, это выглядит примерно так:

export const HomeRoutes:Routes=[
{path:'home', component:HomeComponent}
];

Это приведет вас на домашнюю страницу.

теперь на вашей домашней страницеВы хотите иметь новый <router-outlet></router-outlet>, который позволит вам иметь детей /home.Вам нужно будет добавить детей в маршрут.Это может выглядеть примерно так:

export const HomeRoutes:Routes=[
{path:'home', component:HomeComponent, children:[
    {path:'groups', component:GroupsComponent}
]}
];

Так что теперь, если вы перейдете на /home/groups, вы фактически перейдете к 2 компонентам: HomeComponent и GroupsComponent, которые находятся внутри домашнего компонента.

любой, вы можете иметь столько, сколько пожелаете.

Надеюсь, это объясняет немного лучше.

Полная документация: Здесь

...