2016-10-02 86 views
0

我想创建一个使用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?}"); 
      //}); 




     } 
    } 
} 
+1

你想要加载什么URL? 'localhost/risks'或'localhost/risks/123'? – KTCO

+0

localhost/risks和localhost/ – Mike

+0

请不要在app.html中的路由循环没有显示任何内容,因为路由没有初始化。我只在标题MVC,Angular2和样本 – Mike

回答

-1

我看到你指定路由器的出口在这两个应用程序.html和app.component。我认为这可能会令人困惑。

+0

我注释掉了我的app.component中的router-outlet,并指定了一个模板url指向app.html。这没有任何区别。我不希望数据加载到app.html中,因为app.components中没有提到服务连接。服务连接位于risk-list.component.ts中。所以我需要做的是,当用户输入localhost/risks时,应该加载risk-list.component.ts。预期在risk-list.component.html中有数据输出。 – Mike