AngularCli App路线不能用于生产

时间:2017-12-20 19:38:51

标签: angular routes angular-cli development-environment production

我有一个带有AngularCli的Angular应用程序,具有以下路由配置和NgModule。 Angular App将在ASP.NET Core应用程序内的生产模式下运行

在app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { OneComponent } from './components/one.component';
import { TwoComponent } from './components/open/two.component';

const routes: Routes = [

  { path: '', redirectTo: 'one', pathMatch: 'full' },
  { path: 'one', component: OneComponent },
  { path: 'two', component: TwoComponent },
  { path: '**', redirectTo: 'one' }

];

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

export class AppRoutingModule { }

在app.module.ts上

import { LocationStrategy, PathLocationStrategy } from '@angular/common';
@NgModule({
  declarations: [
    AppComponent,
    OneComponent,
    TwoComponent    
  ]
  imports: [     
    AppRoutingModule,
  ],
  bootstrap: [AppComponent],
  providers: [{ provide: LocationStrategy, useClass: PathLocationStrategy }]
})

在开发模式下路线没问题,但是当我去生产(ng build --prod --aot)时,路线停止工作。 如果我使用HashLocationStrategy路由同时处理开发和生产模式,但我遇到了一些问题,因为有时需要在更改url上的参数时连接两次或三次Url以连接我的Rest Api
问题是PathLocationStrategy给了我想要的行为,但仅限于开发而不是生产。

我需要一个适用于这两种模式的解决方案

任何想法,提前谢谢

更新 如果您使用ASP.NET Core 2.1+,则无需使用URL重写,angular的项目模板将使用NuGetPackage Microsoft.AspNetCore.SpaServices

处理此问题。

3 个答案:

答案 0 :(得分:1)

我最终使用Angular.io网站提供的相同解决方案解决了这个问题 Go here

需要将此添加到我的asp.net核心应用程序web.config文件中:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Angular Routes" 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>

<action type="Rewrite" url="/"/>中的网址应与index.html中的基本href相匹配

答案 1 :(得分:0)

如果您已在IIS中部署了Web应用程序,请尝试放置空的href标记,然后构建应用程序并部署

<base href="">

答案 2 :(得分:0)

服务器上的Angular应用程序的路径是什么?如果index.html文件的初始网址类似于“www.example.com/my/anular/app/”,那么您的index.html中需要<base href="/my/angular/app/">。将选项--base-href /my/angular/app/添加到ng build。前导和尾随斜杠很重要。

相关问题