ASP.Net Core + Angular 2 app /home routing
Asked Answered
O

3

6

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.

Osteotome answered 7/9, 2017 at 22:7 Comment(0)
O
1

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.

Osteotome answered 21/10, 2017 at 16:57 Comment(0)
S
7

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" }); });

Stephaniestephannie answered 21/3, 2018 at 19:9 Comment(0)
O
1

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.

Osteotome answered 21/10, 2017 at 16:57 Comment(0)
B
-5

Is there a reason why you are using asp.net with angular? I HIGHLY suggest you using angular cli. Importing libraries and publishing is very difficult with angular + asp.net.

Using angular cli will also always be "angular"

Barmen answered 7/9, 2017 at 22:23 Comment(3)
Well, that doesn't really answer my question, but OK :-)... I'm learning programming so I rely on what I find online to move on. The project I need to deliver should be a simple combination of ASP.NET Core with Angular2 elements. I'm close to finishing it, but this routing issue keeps me away from setting it up as I'd like it to work. Of course, I already found materials about Angular-CLI so I'll take that as a learning opportunity. Still, I'd appreciate tips to overcome my routing issue :-)Osteotome
The asp page that says "Loading..." is necessary because that is the selector from your component. If the asp page is stuck on "Loading..." then you are not selecting the correct component. Also, if you're using iis, maybe this link would help #22657445Barmen
Also, I think you're missing router-outletBarmen

© 2022 - 2024 — McMap. All rights reserved.