角4路由/ RouterModule影响域后的路径

时间:2018-08-13 21:49:44

标签: angular routes angular-router

我的Angular应用托管在我无法控制的服务器上,并且只能通过导航到此链接来访问。

externalServer.com/myAppName

每当我导航到此链接时,我都会在/#/home之后看到myAppName,但我看到了。

externalServer.com/#/home

问题是myAppName已从路径中删除。我要查看的URL是这个。

externalServer.com/myAppName/#/home

我的问题是这个。 Angular RouterModule或Routes组件是否可能导致路径上的myAppName部分被截断?还是该问题与Angular无关?

我对Angular不够熟悉,无法知道这是路线问题还是完全不同的问题,因此我只是想弄清楚将精力放在哪里。我假设如果Angular可以修复此问题,则可能需要在app.module.ts文件中进行更改,因此我将其发布在下面。感谢您的帮助。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { DesktopUiComponent } from './desktop-ui/desktop-ui.component';
import { MobileUiComponent } from './mobile-ui/mobile-ui.component';
import { RouterComponent } from './router/router.component';


const appRoutes: Routes = [
  { path: 'home', component: RouterComponent },
  { path: '', redirectTo: '/home', pathMatch: 'full' }
];

@NgModule({
  declarations: [
    AppComponent,
    DesktopUiComponent,
    MobileUiComponent,
    RouterComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    RouterModule.forRoot(appRoutes, { useHash: true })
  ],
  exports: [
    RouterModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

1 个答案:

答案 0 :(得分:0)

我能够找到另一条回答我的问题的帖子。链接在下面。

Angular 2 / 4 / 5 - Set base href dynamically

此外,下面是我更新后的app.module.ts文件,其中所做的更改使该应用程序可以在任何起始路径下运行。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { DesktopUiComponent } from './desktop-ui/desktop-ui.component';
import { MobileUiComponent } from './mobile-ui/mobile-ui.component';
import { RouterComponent } from './router/router.component';


const appRoutes: Routes = [
  { path: '', component: RouterComponent }
];

export function getBaseLocation() {
    let paths: string[] = location.pathname.split('/').splice(1, 1);
    let basePath: string = (paths && paths[0]) || '';
    return '/' + basePath;
}

@NgModule({
  declarations: [
    AppComponent,
    DesktopUiComponent,
    MobileUiComponent,
    RouterComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    RouterModule.forRoot(appRoutes)
  ],
  exports: [
    RouterModule
  ],
  providers: [{ provide: APP_BASE_HREF, useFactory: getBaseLocation }],
  bootstrap: [AppComponent]
})
export class AppModule { }