I added to an existing MVC (aspnet core) application some interfaces that use Angular2 for the front end.
but im having an issue, when you access by url or refresh instead of loading the component that corresponds load the home component ignoring the route.
Ex: the app has 2 components, holaComponent, chauComponent.
if i type in url bar
localhost/Admin.mvc/Angular
land in localhost/Admin.mvc/Angular/Hola. Thats Perfect! Hola is my "home" component.
if i type
localhost/Admin.mvc/Angular/Chau
land in localhost/Admin.mvc/Angular/Chau/Hola. Load the Hola component instead of Chau component.
if i type
localhost/Admin.mvc/Angular/Hola
land in localhost/Admin.mvc/Angular/Hola/Hola.
some things for keep in mind:
- Routes using the 'routerLink=""' work fine. the problem only appears when you access by url or refresh.
- Angular2 app is boostrap in a view (view name: Angular).
- Admin.mvc is a controller, using also for non angular views.
routeConfig.cs file:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");
routes.MapRoute(
name: "Homepage",
url: "",
defaults: new { controller = "Account", action = "Login" }
);
routes.MapRoute(
name: "Controller",
url: "{controller}",
defaults: new { action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}.mvc/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
,
constraints: new
{
serverRoute = new ServerRouteConstraint(url =>
{
return !url.PathAndQuery.StartsWith("/Admin.mvc/Angular",
StringComparison.InvariantCultureIgnoreCase);
})
}
);
routes.MapRoute(
name: "spa-fallback",
url: "Admin.mvc/Angular/{*pathInfo}",
defaults: new { controller = "Admin", action = "Angular"});
}
my angular Routing Module
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FlekzComponent } from './ng-flekz.component';
import { HolaComponent } from './ng-flekz-hola.component';
import { ChauComponent } from './ng-flekz-chau.component';
const routes: Routes = [
{ path: '', redirectTo: 'hola', pathMatch: 'full' },
{ path: 'hola', component: HolaComponent },
{ path: 'chau', component: ChauComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class FlekzRoutingModule { }
-sorry for the bad english, is not my native lenguage.
1 Answer 1
Not sure if that's acceptable for you but if you're OK with having a hash in URL you could import like so: RouterModule.forRoot(routes, {useHash: true}). Then you'll have the same base URL for the app (in your case it's Admin.mvc/Angular) and rest of the app will be routed as such:
- Admin.mvc/Angular/#/hola -> HolaComponent
- Admin.mvc/Angular/#/chau -> ChauComponent
Check if you'll need to update base href to whatever path you'll be using.
3 Comments
Explore related questions
See similar questions with these tags.