【问题标题】:ASP.Net Core + Angular 2 app /home routingASP.Net Core + Angular 2 应用程序/home 路由
【发布时间】:2017-09-07 22:07:58
【问题描述】:

我已经为此奋斗了一段时间,并决定写一篇文章。

我正在使用 ASP.Net Core 5.0 和 Angular 2 上的 VS2017 构建一个简单的单页应用程序,其模板取自 ASP.NET Core 模板包。该应用程序应该管理一个联系人列表数据库。

我的想法是默认的起始“/home”页面应该使用 HomeComponent 显示联系人列表。所有路由都可以正常工作,但是当应用程序启动时或每当我尝试路由到“/home”时,它会一直转到 ASP Home 视图的 Index.cshtml 页面,而不是使用 Angular 路由。

知道如何让它始终通过 Angular 吗?我想将 HomeComponent 与 '/home' 路由对齐,但它一直转到 ASP 页面,该页面只显示“正在加载...”,而我并不真正需要(我认为)。

我已经尝试了很多不同的解决方案,但我无法让任何工作。我可能在这里遗漏了一些明显的东西,因为我在这些方面不是太先进,所以如果你能保持基本,请做;-)

这是我在 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 的主页 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>
} 

Aaa 和 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())
        );
    }
}

提前谢谢各位!任何建议将不胜感激。

【问题讨论】:

    标签: asp.net-mvc angular2-routing single-page-application


    【解决方案1】:

    我认为困扰您的是您希望拥有单个应用程序并让 Angular 进行客户端路由并将 WEB.API 调用发布回 .NET Core Web API。 所以,一旦你在像 www.example/subpage 这样的页面上,你按下 F5 重新加载相同的页面,避免被踢回主页。

    解决方案是创建两条 MVC 路由。 第一个路由将处理重定向到 Web.API 的调用,第二个路由将接受任何 Angular URL 请求,并忽略所有内容并将调用转发到 Home 控制器。

    要实现您需要的:

    1. 在 Views\Home\Index.cshtml 中包含你的 Angular 组件标签(我的是 app-root)
    2. 在 Startup.cs 中,在“app.Run”之前添加以下代码
    app.UseMvc(cfg => { cfg.MapRoute( "API", "api/{controller=*}/{action=*}/{id?}"); cfg.MapRoute( "Default", // Route name "{*catchall}", // URL with parameters new { controller = "Home", action = "Index" }); });

    【讨论】:

      【解决方案2】:

      我采用了不同的方法并使用link 下的教程重建了我的应用程序。

      这是一个解决方案,您首先创建 ASP.NET CORE Web App API 接口并在其上安装 Angular。一点点“工程”,直接在 Visual Studio 上工作,并且需要很少的时间来设置。

      【讨论】:

        【解决方案3】:

        您使用 angular 的 asp.net 有什么原因吗?我强烈建议您使用 angular cli。使用 angular + asp.net 导入库和发布非常困难。

        使用 angular cli 也将始终是“angular”

        【讨论】:

        • 嗯,这并不能真正回答我的问题,但是好的 :-)... 我正在学习编程,所以我依靠我在网上找到的东西继续前进。我需要交付的项目应该是 ASP.NET Core 与 Angular2 元素的简单组合。我即将完成它,但是这个路由问题使我无法设置它,因为我希望它可以工作。当然,我已经找到了有关 Angular-CLI 的资料,所以我将把它当作一个学习机会。尽管如此,我还是很感激能解决我的路由问题的提示:-)
        • 显示“正在加载...”的 asp 页面是必要的,因为这是您组件的选择器。如果 asp 页面停留在“正在加载...”,那么您没有选择正确的组件。另外,如果您使用的是 iis,也许这个链接会有所帮助stackoverflow.com/questions/22656945/…
        • 另外,我认为您缺少路由器插座
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-16
        • 2019-07-04
        • 2017-05-30
        • 1970-01-01
        • 2017-06-12
        • 2021-10-13
        • 2021-04-22
        相关资源
        最近更新 更多