【问题标题】:Angular 4 ngx-rocket deep link routing issueAngular 4 ngx-rocket 深度链接路由问题
【发布时间】:2017-10-04 00:06:05
【问题描述】:

我已经使用 ngx-rocket yeoman 生成器成功地为我的 Angular 4 应用程序中的某些页面设置了路由。例如,我创建了一个名为“吃”的页面,当您访问我的主页 www.haakon.io,然后单击“吃”链接时,您将被带到该页面。如果您尝试在浏览器中键入该链接,例如 http://www.haakon.io/eat 并尝试导航到那里,您会看到 404 错误页面。我知道这与深度链接问题有关,但我尝试了一些 angular 1.5 解决方案,但它们不起作用。具体来说,我在 index.html 页面中设置了基本 href:

  <base href="/"/>

这是我的 app-routing.module.ts 文件:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  // Fallback when no prior route is matched
  { path: '**', redirectTo: '', pathMatch: 'full' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: []
})
export class AppRoutingModule { }

这是我的 route.service.ts:

import { Routes } from '@angular/router';

import { ShellComponent } from './shell/shell.component';

/**
 * Provides helper methods to create routes.
 */
export class Route {

  /**
   * Creates routes using the shell component and authentication.
   * @param routes The routes to add.
   * @return {Routes} The new routes using shell as the base.
   */
  static withShell(routes: Routes): Routes {
    return [{
      path: '',
      component: ShellComponent,
      children: routes
    }];
  }

}

最后是我的eat-routing.module.ts:

import { Route } from '../core/route.service';
import { extract } from '../core/i18n.service';
import { EatComponent } from './eat.component';

const routes: Routes = Route.withShell([
  { path: 'eat', component: EatComponent, data: { title: extract('Eat') } }
]);

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
  providers: []
})
export class EatRoutingModule { }

【问题讨论】:

    标签: javascript angular angular-routing yeoman-generator


    【解决方案1】:

    经过更多调查,结果发现一个文件从服务器上删除并影响了服务器级别的默认路由。

    最初我只是想删除这个问题,但决定发布答案以防它对某人有所帮助。

    解决方案是创建一个包含以下内容的 .htaccess 文件,并将其放在主机的根文件夹中:

    # If the request is a file, folder or symlink that exists, serve it up
    RewriteCond %{REQUEST_FILENAME} -s [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^(.+)$ - [S=1]
    
    # otherwise, serve your index.html app
    RewriteRule ^(.+)$ /index.html
    

    现在 www.haakon.io/art 可以通过直接在浏览器中输入或从另一个网站链接来访问。

    【讨论】:

      【解决方案2】:

      我知道这有点老了,但是如果您无法修改 .htaccess,还有一种方法可以让您的 Angular 应用程序使用哈希样式路由而不是 url 路由。它使用的 URL 不是传统的......

      www.haakon.io/#/art

      但它们会绕过大多数可能导致您遇到的问题的服务器配置。

      要使用它,只需像这样将它添加到您的路由器模块导入中......

      RouterModule.forRoot(routes, {useHash: true})

      我最近不得不在一个项目中使用它,因为它是运行简单 http 服务器的服务的 UI,它将 / 之后的所有内容解释为物理文件/文件夹,并且没有 .htaccess。如果用户手动重新加载浏览器并且 URL 不是默认 URL,则使用哈希格式是不混淆服务器的唯一方法。

      【讨论】:

        猜你喜欢
        • 2017-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-08
        • 1970-01-01
        • 1970-01-01
        • 2020-04-12
        相关资源
        最近更新 更多