Angular 2空组件路由

问题描述 投票:5回答:3

我是Angular 2的新手,我对路由有疑问。我有一个app.routing文件,其中我只想要一个路径。

{path: 'signup', component: SignupComponent}

但是,如果我运行此代码,我会收到一个错误:

Error: Uncaught (in promise): Error: Cannot match any routes: ''

所以我决定在''路径上使用一个空组件,它的工作原理与我想要的完全一样。

路由文件:

import {Routes, RouterModule} from '@angular/router';
import {SignupComponent} from "./signup/signup.component";
import {EmptyComponent} from "./empty/empty.component";

const appRoutes:Routes = [
    {path: '', component: EmptyComponent},
    {path: 'signup', component: SignupComponent}
];

export const appRoutingProviders = [];

export const routing = RouterModule.forRoot(appRoutes);

带路由器插座的文件:

<header>
    <div class="btn-wrapper">
        <button class="btn-sign-up btn-fancy" routerLink="/signup">Sign Up</button>
        <button class="btn-sign-in btn-ghost btn-fancy">Sign In</button>
    </div>
    <i class="material-icons more">keyboard_arrow_down</i>
    <router-outlet></router-outlet>
    <div class="overlay" *ngIf="overlay" (click)="close()"></div>
    <div class="tinted"></div>
</header>

我只想要路由器只在“注册”路径上路由SignupComponent。还有另一种方法可以做到这一点,并消除使用空组件?如果这个问题写得不好,我很抱歉,我对StackOverflow很新。

angular angular2-routing
3个回答
5
投票

只需将空路由重定向到注册路由:

const appRoutes:Routes = [
    {path: '', redirectTo: 'signup', pathMatch: 'full'}, 
    {path: 'signup', component: SignupComponent}
];

或者,如果您希望路由器插座为空,直到导航到signup,请将四个完全留空:

const appRoutes:Routes = [
    {path: '', children: []}, 
    {path: 'signup', component: SignupComponent}
];

0
投票
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { DemoComponent } from './demo.component';

const demoRoutes: Routes = [
    { path: '', component: DemoComponent }
];

export const demoRouting: ModuleWithProviders = RouterModule.forChild( demoRoutes );

0
投票

选项1:

如果您知道子路由器插座中没有任何内容可以显示,您可以实际隐藏它。那你就不会得到错误。

<router-outlet *ngIf="hasNoQuestionSelected$ | async"></router-outlet>

我觉得这在技术上比“虚拟组件”更正确,但是绝对有这样的情况,那是好的,合法的,可能更安全。即使在将此作为一种似乎有效的解决方案呈现时,这可能会增加难以调试的竞争条件 - 这可能取决于您如何确定是否显示出口。

很想知道人们是否认为这是一个可怕或合法的解决方案。

PS。不要与Angular的EmptyOutletComponent混淆。这是相关的,但不是一回事,实际上为空路线添加了新的路由器插座。

--

选项2:

您可以拥有仅具有路径且没有子项,组件或重定向的路由。

您仍然可以查询ActivatedRoute快照并遍历树以查找所需的参数 - 它们仍然存在。但是如果没有<router-outlet>,路由器将不会尝试实际做任何事情 - 这取决于你。或者您仍然可以定义一个组件,然后根据条件(例如屏幕宽度)决定是否显示或隐藏router-outlet以消耗它。

我为什么要这样你可能会问?有时针对不同屏幕尺寸的响应式设计,我发现自己需要完全不同的行为。有时,这需要“钻研”到snapshot.children[0].routeData来提取URL参数。然后我将在主要组件中自己显示组件。

只是将其添加为某些案例的另一种选择。

{
    path: 'contactus',
    component: ContactUsComponent,

    children: [
        {
            path: 'topics',
            pathMatch: 'full',
            redirectTo: '/support/contactus'
        },
        {
            path: ':category',

            children: 
            [
                {
                    path: ':question'
                    // component: ContactUsFormComponent
                }
            ]
        }
    ]
},
© www.soinside.com 2019 - 2024. All rights reserved.