我想創建一個使用ASP.Net核心應用的Angular 2應用程序。路由似乎不起作用。當我執行應用程序時,app.html頁面顯示在startup.cs文件中。我應該能夠通過URL導航時,我鍵入例如本地主機/風險等請不要在app.html路由循環不顯示任何內容,因爲路由沒有初始化。我只能用標題MVC,Angular2和示例看到app.html。在ASP.Net核心的角2路由
有人可以幫我解決這個問題嗎?
Application Folder Structure screenshot
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from '../app.component';
import { RiskListComponent } from './risks/risk-list.component';
import { RiskDetailsComponent } from './risks/risk-detail.component';
import { RiskService } from './risks/risk.service';
import {
LocationStrategy,
HashLocationStrategy
} from '@angular/common';
import { routing,
appRoutingProviders} from './app.routing';
@NgModule({
imports: [BrowserModule, FormsModule, routing],
declarations: [AppComponent, RiskListComponent, RiskDetailsComponent],
providers: [
appRoutingProviders, RiskService, { provide: LocationStrategy, useClass: HashLocationStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule { }
app.routing.ts
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { RiskListComponent } from './risks/risk-list.component';
import { RiskDetailsComponent } from './risks/risk-detail.component';
const appRoutes: Routes = [
{ path: '', pathMatch: 'full', component: RiskListComponent },
{ path: 'risks/:id', component: RiskDetailsComponent },
];
export const appRoutingProviders: any[] = [
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
風險list.component.html
<h3 class="first">{{title}}</h3>
<!--[rows]="5" [paginator]="true" [pageLinks]="2" [rowsPerPageOptions]="[5,10,20]"-->
<!--<p-paginator rows="10" totalRecords="100" pageLinkSize="3"></p-paginator>-->
<div>{{risks | json}}</div>
<p-dataTable [value]="risks" [paginator]="true" rows="5" totalRecords="100" pageLinkSize="3" [rowsPerPageOptions]="[5,10,20]" [sortMode]="multiple" sortField="inceptionDate" [sortOrder]="1" >
<header>List of Risks</header>
<!--<footer>Choose from the list.</footer>-->
<p-column field="reference" header="Reference (contains)" [filter]="true" sortable="true"></p-column>
<p-column field="insuredName" header="Insured Name (contains)" [filter]="true" sortable="true"></p-column>
<p-column field="inceptionDate" header="Inception Date (contains)" [filter]="true" sortable="true"></p-column>
<p-column field="riskType" header="Risk Type (contains)" [filter]="true" sortable="true"></p-column>
<p-column field="status" header="Status (contains)" [filter]="true" sortable="true"></p-column>
<p-column field="grossPremium" header="Gross Premium (contains)" [filter]="true" sortable="true"></p-column>
<p-column field="allocatedTo" header="Allocated To (contains)" [filter]="true" sortable="true"></p-column>
<p-column field="allocatedCompany" header="Allocated Company (contains)" [filter]="true" sortable="true"></p-column>
</p-dataTable>
risk.ts
export class Risk {
riskId: number;
reference: string;
insuredName: string;
inceptionDate: string;
riskType: string;
status: string;
grossPremium: number;
allocatedTo: string;
allocatedCompany: string;
}
app.component.ts
import { Component } from '@angular/core';
import { DataTable, Column } from 'primeng/primeng';
import { Router } from '@angular/router';
import { Routes, RouterModule } from '@angular/router';
import { RiskListComponent } from './components/risks/risk-list.component';
import { RiskDetailsComponent } from './components/risks/risk-detail.component';
import { ModuleWithProviders } from '@angular/core';
import './rxjs-operators';
//import { RiskService } from './components/risks/risk.service';
@Component({
selector: 'my-app',
template: `
<div>
<h1>{{pageTitle}}</h1>
<rm-risks> </rm-risks>
</div>
<nav>
<a routerLink="/dashboard" >Dashboard</a>
<a routerLink="/risks" >Risks</a>
</nav>
<div>
<router-outlet> </router-outlet>
</div>
`
// <a routerLink="/riskdetails" routerLinkActive="active">RiskDetails</a>
//< a routerLink="/welcome" routerLinkActive="active" > Welcome < /a>
//,
//directives: [RiskListComponent, DataTable, Column],
})
export class AppComponent {
pageTitle: string = 'Test UK Trader';
}
app.html
<div class="page-header">
<h1>
MVC, Angular2
<br>
<small>Sample</small>
</h1>
</div>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">
<span class="glyphicon glyphicon-sunglasses"></span>
</a>
</div>
<ul *ngIf="routes != null" class="nav navbar-nav">
<li *ngFor="#rt of routes" [class.active]="getLinkStyle(rt)">
<a [routerLink]="[rt.name]">{{rt.name}}</a>
</li>
</ul>
</div>
</nav>
<div class="content padding has-header">
<router-outlet></router-outlet>
</div>
startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Glimpse;
using System.IO;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.Extensions.FileProviders;
using Microsoft.DotNet.InternalAbstractions;
namespace AspNetCoreAngularDemo1
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
// services.AddGlimpse();
services.AddMvc();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.Use(async (context, next) =>
{
await next();
// If there's no available file and the request doesn't contain an extension, we're probably trying to access a page.
// Rewrite request to use app root
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/app/app.html"; // Put your Angular root page here
context.Response.StatusCode = 200; // Make sure we update the status code, otherwise it returns 404
await next();
}
});
// Serve wwwroot as root
app.UseFileServer();
// Serve /node_modules as a separate root (for packages that use other npm modules client side)
app.UseFileServer(new FileServerOptions()
{
// Set root of file server
// FileProvider = new PhysicalFileProvider(Path.Combine(environment.ApplicationBasePath, "node_modules")),
// Only react to requests that match this path
RequestPath = "/node_modules",
// Don't expose file system
EnableDirectoryBrowsing = false
});
//app.UseMvc(routes =>
//{
// routes.MapRoute("default",
// "{controller=Home}/{action=Index}/{id?}");
// routes.MapRoute("spa-fallback",
// "{*anything}",
// new { controller = "Home", action = "Index" });
// routes.MapWebApiRoute("defaultApi",
// "api/{controller}/{id?}");
//});
}
}
}
你想要加載什麼URL? 'localhost/risks'或'localhost/risks/123'? – KTCO
localhost/risks和localhost/ – Mike
請不要在app.html中的路由循環沒有顯示任何內容,因爲路由沒有初始化。我只在標題MVC,Angular2和樣本 – Mike