【问题标题】:Can't navigate to other pages in Angular 5 application, after the deploying project (ng build)部署项目(ng build)后,无法导航到 Angular 5 应用程序中的其他页面
【发布时间】:2018-05-31 06:45:12
【问题描述】:

当我使用以下命令测试我的 Angular 应用程序 (v5) 时:

ng serve --open

我可以导航到我的应用程序的任何注册路径。当我想在构建过程之后通过以下方式为我的应用程序提供服务时:

ng buildng build --prod

在导航到任何路线后,我收到 404 错误。如果要阅读official tutorial,项目部署不应该有任何复杂的操作。

我搜索了一下,发现建议在build命令中添加--base-href=/选项,但也没有成功。

我正在使用下一个 HTTP 服务器:https://www.npmjs.com/package/http-server

对我的可能问题:

Q1:您如何为 Angular 应用提供服务?

A1:在应用目录下使用NPM-package的http-server --cors命令,所以--base-href引用正确

Q2:你的路由配置是什么(源码)?

A2:我的路线很简单,因为我正在学习Angular v5教程,所以不要指望有什么特别之处,源代码在下:

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SalesComponent }       from './sales/sales.component';
import { ConsumersComponent }   from './consumers/consumers.component';

const routes: Routes = [
    { path: 'consumers' , component: ConsumersComponent },
    { path: 'sales', component: SalesComponent }
];

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

export class AppRoutingModule { }

AppRoutingModuleapp.modude.ts 文件中提供(imports: in @NgModule)。

Q3:您的 Angular 应用程序是否依赖于后端(服务器端应用程序)?

A3:它没有。它只有用于数据模拟的模拟对象。它们被定义为分离类中的静态数据。我与官方网站上的 Angular 教程相去甚远。只是想用我最喜欢的微型 HTTP 服务器提供 ng build --prod 版本。

所以,当使用ng serve 命令时,我可以导航到其他页面,但在构建项目后我不能这样做。教程提供了描述,我可以将构建文件作为静态文件提供给任何 HTTP 服务器,但对我来说没有成功。

我该如何解决我的问题?

谢谢

【问题讨论】:

    标签: angular deployment build routing production


    【解决方案1】:

    由于official deployment guide,我已经解决了我的问题。

    您应该配置您的 HTTP 服务器以遵循 前端控制器模式。我已经用 nginx 服务器对其进行了测试,使用下一个配置:

    server {
        listen 80 default_server;
        root /var/www/html;
        index index.html index.htm;
        server_name localhost;
        location / {
            try_files $uri $uri/ /index.html;        
        }
    }   
    

    现在一切正常。

    如果您使用的是 Apache 服务器或 web.config 文件,如果 IIS 是您的 HTTP 服务器等等,您可以对 .htaccess 文件执行相同的操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      相关资源
      最近更新 更多