首页 > 解决方案 > Angular Routing 在 URL 地址栏上不起作用

问题描述

我用路由组件制作了一个 Angular 项目。我已经处理了一些 URL 处理,比如用户手动点击 URL:如果 URL 存在,它会转到app-routing-module.ts中定义的 URL 组件,如果 URL 不存在,它会显示代码 PagenotFoundComponent 中定义的错误页面。例如

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

import {HomeComponent} from './component/home.component';
import {AboutusComponent} from './component/aboutus.component';
import {SupportComponent} from './component/support.component';
import {PurchaseComponent} from './component/purchase.component';
import {PagenotfoundComponent} from './component/pagenotfound.component';
import {HowitworksComponent} from './component/howitworks.component';
import {ProductComponent} from './component/product.component';
import { ProductVarientDetailsComponent } from './component/product-varient-details.component';

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full'},
  { path: 'home', component: HomeComponent},
  { path: 'about-us', component: AboutusComponent},
  { path: 'how-it-works', component: HowitworksComponent},
  { path: 'support', component: SupportComponent},
  { path: 'purchase', component: PurchaseComponent},
  { path: 'product/:name/details', component: ProductComponent},
  { path: 'product-variants', component: ProductVarientDetailsComponent},
  { path: '**', component: PagenotfoundComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
export const routingComponents = [HomeComponent, AboutusComponent, SupportComponent,
                                  PurchaseComponent, PagenotfoundComponent, HowitworksComponent,
                                  ProductComponent, ProductVarientDetailsComponent];

因此,当我手动点击 localhost:4200/home 时,它​​会显示 HomeComponent 页面,如果我这样做 localhost:4200/sdnbgbdfgbh,它会显示本地服务器上的 PagenotfoundComponent 页面。

然后我去了这个链接:https ://angular.io/guide/deployment来部署我的 Angular 应用程序。我按照文档中的步骤进行操作。说。

我的应用程序现在可以完全运行,但是当我手动输入一些 url 时,它会显示 Apache Server Page Not Found。只是这件事在 Angular 应用程序中不起作用。

我已将我的应用程序部署在 80 端口的 Apache 服务器上的 AWS EC2 上。

标签: amazon-ec2deploymentangular6angular-routing

解决方案


尝试重定向到404这样的路径:

const routes: Routes = [
   ...otherRoutes
   { path: '404', component: PagenotfoundComponent},
   { path: '**', redirectTo: '404'}
];

如果不起作用,请尝试根据Angular 文档配置 .htaccess :

RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

请记住,所有路径命中都应index.html在 apache 配置中通过。

或者试试这个文档,我希望它有帮助:

https://github.com/mgechev/angular-seed/wiki/Deploying-prod-build-to-Apache-2

推荐阅读