Search code examples
angularangular-routing

Routing not working in production


I was developing a web application in Angular 2, its working fine in my localhost, but when i hosted in production environment its not working my sub-domain is replacing with empty string

My production server is http://foobar:8888/Hrms

where "Hrms" is sub-domain that is where i hosted my "publish files"

when i run in local the url was : http://localhost:50739/#/access/login and in server the sub-domain missing automatically : http://foobar:8888/#/

i tried http://foobar:8888/hrms/#/access/login but it still going to http://foobar:8888/#/ automatically

Code

var domainName = "";
if (location.hostname !== "localhost")
    domainName = "HRMS/";

const appRoutes: Routes = [
{
    path: "access", component: AccessComponent,
    children: [
        { path: "", redirectTo: "login", pathMatch: "full" },
        { path: domainName + "login", component: LoginComponent, data: { title: "Login" }, canActivate: [UserGuard] },
        { path: domainName + "forgot-password", component: ForgotPasswordComponent, data: { title: "Forgot Password" }, canActivate: [UserGuard] },
        { path: domainName + "not-found", component: PageNotFoundComponent, data: { title: "Page Not Found" } },
        { path: domainName + "lock-me/:path", component: LockComponent, data: { title: "Locked" }, canActivate: [LockGuard] }
    ]
},
{
    path: "app", component: LayoutComponent,
    canActivate: [AuthGuard],
    children: [
        { path: "", redirectTo: "getting-started", pathMatch: "full" },
        { path: domainName + "dashboard", component: DashboardComponent, data: { title: "Dashboard" } },
        { path: domainName + "getting-started", component: GettingStartedComponent, data: { title: "Getting Started" } },
        { path: domainName + "accounts", component: AccountsComponent, data: { title: "Accounts" } },
        { path: domainName + "organization", component: OrganizationComponent, data: { title: "Organization" } },
        { path: domainName + "interviews", component: InterviewsComponent, data: { title: "Interviews" } }
    ]
},
    { path: "", redirectTo: domainName + "access/login", pathMatch: "full" },
    { path: "**", redirectTo: domainName + "access/not-found", pathMatch: "full" }
];

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes, { useHash: true })
    ],
    exports: [
        RouterModule
    ]
})
export class AppRouting { }

Please let me know, when did i do wrong Thanks.


Solution

  • You have to change your base tag in your index.html file:

    <base href="/"> to <base href="/hrms">

    This tag is used by angular router to know where is the base of every route, that's why it's not working in production while it works in dev.