繁体   English   中英

.NET MVC 5 中的 Angular 6 应用程序,角度路由不起作用

[英]Angular 6 app in .NET MVC 5, angular routing doesn't work

我在现有的 .NET MVC 5 应用程序中嵌入了 Angular 6 应用程序。 我在 MVC 应用程序 (RouteConfig.cs) 中添加了一个指向 Home/Index 的后备路由,因此“未知”路由将传递给 Angular 应用程序的路由器模块 (app.routes.ts)。 Angular 应用程序的路由似乎没有触发,与路径关联的组件未加载。

IDE 是 Visual Studio 2017 Enterprise 15.6.7,MVC 应用程序是标准的 .NET Web 应用程序(不是 .NET Core),MVC 5.2.3.0; Node.js 8.11.3、npm 6.3.0、Typescript 2.9.2、Angular CLI 6.0.8、Angular 6.0.3; 引导程序 3.3.7,jquery 3.3.1; 操作系统:Win 10 x64。

MVC 应用程序的 RouteConfig.cs 如下; 包罗万象的路线在底部。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Ang2Mvc5_0
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "mvc",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

            // This is a catch-all for when no other routes match the request; let the Angular 2 router take care of it...
            routes.MapRoute(
                name: "default",
                url: "{*url}",
                defaults: new { controller = "Home", action = "Index" } // The view that bootstraps Angular 2 app
            );
        }
    }
}

当我创建 Angular 应用程序(使用 CLI)时,Typescript 的 package.json 条目默认为 2.7.2; package.json 在下面,ngf-bootstrap 条目特定于 PluralSight 教程。

我错过了什么吗?

{
    "name": "temp-app",
    "version": "0.0.0",
    "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build",
        "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e"
    },
    "private": true,
    "dependencies": {
        "@angular/animations": "^6.0.3",
        "@angular/common": "^6.0.3",
        "@angular/compiler": "^6.0.3",
        "@angular/core": "^6.0.3",
        "@angular/forms": "^6.0.3",
        "@angular/http": "^6.0.3",
        "@angular/platform-browser": "^6.0.3",
        "@angular/platform-browser-dynamic": "^6.0.3",
        "@angular/router": "^6.0.3",
        "core-js": "^2.5.4",
        "ngf-bootstrap": "0.0.5",
        "rxjs": "^6.0.0",
        "toastr": "^2.1.4",
        "zone.js": "^0.8.26"
    },
    "devDependencies": {
        "@angular-devkit/build-angular": "~0.6.8",
        "@angular/cli": "~6.0.8",
        "@angular/compiler-cli": "^6.0.3",
        "@angular/language-service": "^6.0.3",
        "@types/jasmine": "~2.8.6",
        "@types/jasminewd2": "~2.0.3",
        "@types/node": "~8.9.4",
        "codelyzer": "~4.2.1",
        "jasmine-core": "~2.99.1",
        "jasmine-spec-reporter": "~4.2.1",
        "karma": "~1.7.1",
        "karma-chrome-launcher": "~2.2.0",
        "karma-coverage-istanbul-reporter": "~2.0.0",
        "karma-jasmine": "~1.1.1",
        "karma-jasmine-html-reporter": "^0.2.2",
        "protractor": "^5.4.0",
        "ts-node": "~5.0.1",
        "tslint": "~5.9.1",
        "typescript": "~2.7.2"
    }
}

app.routes.ts 在下面; 这真的很简单,到目前为止,我在应用程序开发方面还没有取得太大进展。

import { NgModule } from '@angular/core'
import { Routes, RouterModule } from '@angular/router'

import { EventsListComponent } from './events/events-list.component'
import { EventDetailsComponent } from './events/event-details/event-details.component'

const routes: Routes = [
    {
        path: 'events',
        component: EventsListComponent
    },
    {
        path: 'events/:id',
        component: EventDetailsComponent
    },
    {
        path: '',
        redirectTo: '/events'
    }
];

@NgModule({
    imports: [RouterModule.forRoot(routes, { enableTracing: true })],
    exports: [RouterModule]
})

export class AppRoutingModule {
}

EventsAppModule 在下面; 注意@第 16 行,我已经导入了 AppRoutingModule (app.routes.ts),我可以评论此行以禁用路由。

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { EventsAppComponent } from './events-app.component';
import { EventsListComponent } from './events/events-list.component';
import { EventThumbnailComponent } from './events/event-thumbnail.component';
import { EventDetailsComponent } from './events/event-details/event-details.component';
import { NavBarComponent } from './nav/navbar.component';
import { EventService } from './events/shared/event.service';
import { ToastrService } from './common/toastr.service';
import { AppRoutingModule } from './app.routes';

@NgModule({
    imports: [
        BrowserModule
        , AppRoutingModule
    ],
    declarations: [
        EventsAppComponent,
        EventsListComponent,
        EventThumbnailComponent,
        EventDetailsComponent,
        NavBarComponent
    ],
    providers: [
        EventService,
        ToastrService
    ],
    bootstrap: [EventsAppComponent]
})

export class EventsAppModule { }

如前所述,当尝试使用路由时,在应用程序的主要组件/页面中使用<router-outlet></router-outlet>标记,EventsListComponent 不会加载(我得到一个空白页面)。 如果我从应用程序模块中注释 AppRoutingModule 并切换到应用程序主组件中的<events-list></events-list>标记,EventsListComponent 加载正常(它显示事件列表,每个事件都封装在 EventThumbnailComponent 中)。

此外,它在我运行时不会加载http://localhost:39420/events 它默认为 root,例如,localhost:39420/...如果我在 url 中键入“/events”,我不会收到错误,只是一个空白页面。 如果我尝试获取 EventDetailsComponent,再次使用 localhost:39420/events/1...,它只会呈现一个空白页面。

redirectTo需要路由器应该导航到的确切路径。 因此它需要一个/ before 您可能已经定义的路由路径。

在路由配置中将redirectTo: 'events'替换为redirectTo: '/events' ,它应该正确加载EventsListComponent组件。

还要添加一个pathMatch: 'full'到这条路线:

    {
        path: '',
        redirectTo: '/events',
        pathMatch: 'full'
    }

这是一个可以帮助您解决问题的StackBlitz 项目

所以这就是当没有其他路由匹配请求时你必须捕获的所有内容,以便 Angular 可以处理它。

// This is a catch-all for when no other routes match the request; let the Angular 2 router take care of it...
            routes.MapRoute(
                name: "default",
                url: "{*url}",
                defaults: new { controller = "Home", action = "Index" } // The view that bootstraps Angular 2 app
            );

您需要删除默认值,以便它看起来像这样。 并且不要为角度创建控制器/视图。

// This is a catch-all for when no other routes match the request; let the Angular 2 router take care of it...
            routes.MapRoute(
                name: "default",
                url: "{*url}",// you don't need a view
            );

运行命令后

ng build --prod

将 dist 文件复制到包含您的 mvc 应用程序根目录的目录 ex(myangularapp) 中。 您将需要更改基本标签的 href 属性,以便运行

ng build --prod --base-href=/myangularapp/

然后,您可以将 web.config 文件添加到保存角度文件 (myangularapp) 的目录中。 下面的示例。

<?xml version="1.0"?>
<configuration>
  <system.web></system.web>
  <system.webServer>
    <rewrite>
      <rules>
        <!--Redirect selected traffic to index -->
        <rule name="Index Rule" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          </conditions>
          <action type="Rewrite" url="index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM