Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Core + Angular 2 app /home routing

I've been fighting with this for a while now and decided to write a post.

I'm building a simple Single Page Application using VS2017 on ASP.Net Core 5.0 and Angular 2 over a template taken from ASP.NET Core Template Pack. The app is supposed to manage a contact list database.

The idea I have in mind is that the default starting '/home' page should be displaying the list of contacts using HomeComponent. All routing works fine, but when app is getting started or whenever I'm trying to route to '/home', it keeps going to ASP Home view's Index.cshtml page instead of using Angular routing.

Any idea how to make it go through Angular at all times? I wanted to align the HomeComponent with '/home' route but instead it keeps going to ASP page which is only there to say 'Loading...' which I don't really need (I think).

I've tried a lots of different solution but I wasn't able to get anything to work. I might be missing something obvious here as I'm not too advanced on these grounds, so if you can keep it basic, please do ;-)

Here's my Configure method from Startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true
            });
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index" });

            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index",});
        });
    }

app.module.shared.ts:

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { DetailsComponent } from './components/details/details.component';
import { EditComponent } from './components/editContact/editContact.component';
import { NewContactComponent } from './components/newContact/newContact.component';
import { HomeComponent } from './components/home/home.component';
import { ContactServices } from './services/services';

export const sharedConfig: NgModule = {
bootstrap: [ AppComponent ],
declarations: [
    AppComponent,
    NavMenuComponent,
    DetailsComponent,
    EditComponent,
    NewContactComponent,
    HomeComponent
],
providers: [ContactServices],
imports: [
    RouterModule.forRoot([
        { path: '', redirectTo: 'home', pathMatch: 'full' },
        { path: 'home', component: HomeComponent },
        { path: 'details', component: DetailsComponent },
        { path: 'new', component: NewContactComponent },
        { path: '**', redirectTo: 'home' }
    ])
]};

ASP's Home Index.cshtml:

@{
ViewData["Title"] = "Home Page";
}
<app>Loading...</app>

<script src="~/dist/vendor.js" asp-append-version="true"></script>
@section scripts {
<script src="~/dist/main-client.js" asp-append-version="true"></script>
} 

Aaaand home.component.ts:

import { Component } from '@angular/core';
import { ContactServices } from '../../services/services';
import { Response } from '@angular/http';

@Component({
selector: 'home',
templateUrl: './home.component.html'
})
export class HomeComponent {
public ContactList = [];
public constructor(private conService: ContactServices) {
    this.conService.getContactList()
        .subscribe(
        (data: Response) => (this.ContactList = data.json())
        );
    }
}

Thanks in advance guys! Any advice will be appreciated.

like image 600
WAR Avatar asked Sep 07 '17 22:09

WAR


2 Answers

I think that what is troubling you is that you wish to have Single App and have Angular doing client routing and posting WEB.API calls back to .NET Core Web API. So, once you are on some page like www.example/subpage, and you press F5 to reload the same, avoid being kicked back to the homepage.

The solution is to create two MVC routes. The first route will deal with redirecting a call to Web.API and the second one will accept any Angular URL request, and just ignore everything and forward the call to the Home controller.

To achieve that you need:

1. In Views\Home\Index.cshtml include your Angular component tag (my is app-root)
2. In Startup.cs, just before "app.Run" add the following code
app.UseMvc(cfg => { cfg.MapRoute( "API", "api/{controller=*}/{action=*}/{id?}"); cfg.MapRoute( "Default", // Route name "{*catchall}", // URL with parameters new { controller = "Home", action = "Index" }); });

like image 176
Hrvoje Matić Avatar answered Nov 12 '22 19:11

Hrvoje Matić


I took different approach and rebuilt my application using the tutorial found under this link.

It is a solution where you first create ASP.NET CORE Web App API interface and install Angular over it. A little bit of 'engineering', works directly off Visual Studio and takes little time to set up.

like image 1
WAR Avatar answered Nov 12 '22 18:11

WAR