加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 从MVC站点路由到Angular 2应用程序

发布时间:2020-12-16 09:55:51 所属栏目:asp.Net 来源:网络整理
导读:在我一直寻求以某种方式从传统的MVC网站路由到一个逐页的Angular 2 SPA我最终得出的结论是,最好立即使用Angular 2路由,即没有查询参数转换为有效的Angular 2路由,因为事实证明这是一场彻头彻尾的噩梦. 在我的遗留Web应用程序中,计划是通过重定向到AppControl
在我一直寻求以某种方式从传统的MVC网站路由到一个逐页的Angular 2 SPA我最终得出的结论是,最好立即使用Angular 2路由,即没有查询参数转换为有效的Angular 2路由,因为事实证明这是一场彻头彻尾的噩梦.

在我的遗留Web应用程序中,计划是通过重定向到AppController上的相应操作来替换控制器操作代码,例如,

public ActionResult Action1(int param1,int param2)
{
    return RedirectTo("Action1","App",new { param1,param2 });
}

AppController位于自己的区域(Areas.Web)中,该区域还包含Angular 2应用程序

public class AppController : Controller
{
    public ActionResult Index()
    {
        return new FilePathResult("~/Areas/Web/index.html","text/html");
    }

    public ActionResult Action1(int param1,int param2)
    {
        return Redirect($"/Areas/Web#/{param1}/{param2}/action1");
    }
}

在index.html中,我将基本href设置为

<base href="/Areas/Web/">

所以我的想法是让ASP.NET MVC抓住index.html并将其发送到浏览器,包括应该评估的哈希位置

/<param1>/<param2>/action1

在Angular方面,对吧?

在我的bootstrap代码中,我确保使用了HashLocationStrategy,

bootstrap(AppComponent,[provide(LocationStrategy,{ useClass: HashLocationStrategy })])
    .then(success => console.log('Bootstrap success'))
    .catch(error => console.log(error));

app.component.ts的路由如下:

@RouteConfig([
    { path: '/:param1/:param2/action1,name: 'Action1',component: Action1Component}
])

我认为这个设置应该正确地路由到Action1Component,但事实并非如此.路由配置完全被忽略,从不调用Action1的构造函数.

我哪里出错了?

编辑:Angular应用程序运行后实际工作的是

http://legacy.com/Areas/Web/<param1>/<param2>/action1

没有# – 但按F5显然会打破这个策略.因此,不仅包含散列符号的URL是无效路由,而且没有散列标记的URL完全有效.我糊涂了….

解决方法

好的,得到了??这个,这要归功于 this answer.诀窍是,除了引导应用程序之外,永远不要提供ROUTER_PROVIDERS:

import { bootstrap } from 'angular2/platform/browser';
import { provide } from 'angular2/core';
import { HTTP_PROVIDERS } from 'angular2/http';
import { 
  ROUTER_PROVIDERS,LocationStrategy,HashLocationStrategy
} from 'angular2/router';
import { AppComponent } from './app.component';

bootstrap(AppComponent,[ 
    ROUTER_PROVIDERS,HTTP_PROVIDERS,provide(LocationStrategy,{ useClass: HashLocationStrategy }
)])
.then(success => console.log('Bootstrap success'))
.catch(error => console.log(error));

我的猜测是,与注入组件的任何其他服务一样,如果在组件装饰器的providers部分中声明ROUTER_PROVIDERS,则会获得一个新的Router实例,从而覆盖为HashLocationStrategy配置的实例,并且作为PathLocationStrategy是默认情况下,你就是这样.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读