【问题标题】:how to enable deeplinking in angular4如何在 Angular 4 中启用深度链接
【发布时间】:2017-10-27 21:44:06
【问题描述】:

我正在尝试在我的 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 文件已导入路由器文件,但这仍然不起作用.. 我如何在此处启用深度链接?

【问题讨论】:

标签: angular angular-routing angular4-router


【解决方案1】:

我认为您需要重写 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>

【讨论】:

    【解决方案2】:

    我希望您可能已经解决了您的问题。

    解决方案是我使用的 HashLocationStrategy。

    RouterModule.forRoot(appRoutes, {useHash: true});
    

    这会导致所有应用的 url 都是 index.html,后跟“#”,然后是路由信息。

    由于您总是要访问 index.html,因此无论路由如何,您都不会得到任何有效 URL 的 404。

    【讨论】:

      【解决方案3】:

      如果你有一个空路径路由 '' 没有孩子,你应该使用 pathMatch: 'full'

        {
          path: '',
          component: TodosComponent,
          pathMatch: 'full'
        },
      

      否则每条路径都会匹配,路由器将搜索(不存在的)子路由与路径的其余部分匹配。

      如cmets中提到的,如果你使用PathLocationStrategy(默认),你需要配置你的服务器来支持它。

      你可以通过切换到HashLocationStrategy来检查服务器是否是罪魁祸首

      export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, {useHash: true});
      

      路由看起来不同,所以当您直接输入旧路由(没有#)时,不要指望它们会起作用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-28
        • 1970-01-01
        • 2018-10-07
        • 2020-08-13
        • 2013-08-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多