我是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的新手。
发布于 2016-09-25 05:22:57
只需将您的空路由重定向到注册路由:
const appRoutes:Routes = [
{path: '', redirectTo: 'signup', pathMatch: 'full'},
{path: 'signup', component: SignupComponent}
];或者,如果您希望在导航到signup之前路由器插座为空,请将这四个选项完全保留为空:
const appRoutes:Routes = [
{path: '', children: []},
{path: 'signup', component: SignupComponent}
];发布于 2019-02-20 07:04:25
选项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
}
]
}
]
},发布于 2017-06-07 21:50:31
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 );https://stackoverflow.com/questions/39680916
复制相似问题