我正在尝试在我的angular4应用程序中实现简单路由,但是深层链接无法正常工作的问题。
例如,我有一个About组件和一个Homepage(todos)组件,我的app.routing.ts文件如下:
import { Routes, RouterModule } from '@angular/router';
import { ModuleWithProviders } from '@angular/core';
import { TodosComponent } from './todos/todos.component';
import { AboutComponent } from './about/about.component';
import { CallbackComponent } from './callback/callback.component';
const appRoutes: Routes = [
{
path: '',
component: TodosComponent
},
{
path: 'about',
component: AboutComponent
},
{
path: 'callback',
component: CallbackComponent
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
现在,当我从routerLink点击应用程序时导航适用于这些组件,但如果我直接在浏览器中输入URL,我将获得404 ..
这打破了我的身份验证来源的回调:(
我的app.module.ts文件导入了路由器文件,但是这仍然不起作用..如何在这里启用深层链接?
如果你有一个空路径路线''
没有孩子,你应该使用pathMatch: 'full'
{
path: '',
component: TodosComponent,
pathMatch: 'full'
},
否则每个路径都匹配,路由器将搜索(不存在的)子路由以寻找与路径其余部分的匹配。
如评论中所述,如果您使用PathLocationStrategy
(默认),则需要配置服务器以支持它。
您可以通过切换到HashLocationStrategy
来检查服务器是否是罪魁祸首
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, {useHash: true});
路线看起来不同,所以当您直接输入时,不要指望旧路线(没有#
)。
我希望你可能已经解决了你的疑问。
解决方案是我使用HashLocationStrategy。
RouterModule.forRoot(appRoutes, {useHash: true});
这导致所有app url为index.html,后跟“#”,然后是路由信息。
由于您始终使用index.html,因此无论路由如何,您都不会获得任何有效URL的404。
我认为你需要重写URL。在IIS中,它将是这样的:
<system.webServer>
<rewrite>
<rules>
<rule name="Angular" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>