Angular 4 - RouterOutlet 404错误

时间:2018-02-08 11:00:20

标签: angular routing angular4-router

我的角度4应用程序托管在一个'网站'作为一个应用程序'在IIS中,让我们说“我的应用程序”。并且我使用此命令使用angular-cli生成了生成版本:

ng build --prod --base-href=/MyApp/

我还在IIS中配置了Url重写,以下是web.config

旁边的index.html文件
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="AngularJS 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="/MyApp/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

以下是我的主要应用程序路由,它基本上有不同模块的入口点及其自己的路径:

@NgModule({
  imports: [
    RouterModule.forRoot([
      { path: 'vm', redirectTo: 'vm/vehicles', pathMatch: 'full' },
      { path: 'rp', redirectTo: 'rp/gantt', pathMatch: 'full' },
      { path: '', redirectTo: 'rp/gantt', pathMatch: 'full' },
      { path: '404', component: PageNotFoundComponent },
      { path: '**', redirectTo: '404' }
    ]
    )
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule { }

问题是,如果我使用此网址http://localhost:8181/MyApp/vm访问该应用,则应用加载正常,但必须为<router-outlet></router-outlet>配置组件的vm/vehicles不会加载,它会在<router-outlet>中显示404组件,并且网址会更改为http://localhost:8181/MyApp/404

以下是vm模块的路由:

const moduleName = 'vm';

const routes: Route[] = [
      { path: 'vehicles', component: VehicleComponent },
      { path: 'standards', component: StandardsComponent }
    ];

 routes.forEach((item) => {
      item.path = moduleName + '/' + item.path;
  });

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

1 个答案:

答案 0 :(得分:0)

问题实际上是代码的这一部分:

 routes.forEach((item) => {
      item.path = moduleName + '/' + item.path;
  });

我不知道确切的原因,因为我们只是动态地改变路径但是角度不接受它,以下代码有效:

const routes: Route[] = [
      { path: 'vm/vehicles', component: VehicleComponent },
      { path: 'vm/standards', component: StandardsComponent }
    ];