@ Component中的Angularjs2'templateUrl' - 如何显示剃刀视图

时间:2017-04-16 15:53:34

标签: asp.net-mvc-5 angular2-routing angular2-template angular2-services angular2-directives

如何在@Component的'templateUrl'中呈现ASP.NET MVC5 Razor View(.cshtml)。使用'/ Home / Index'时,页面会挂起。

import { Component, OnInit } from '@angular/core';
import { Product } from './model';
import { InventoryService } from './dataService';

@Component({
    selector: 'my-app',
    template: `<ul>
        <li *ngFor="let product of products">
            <h4>{{product.getProducts()}}</h4>
        </li>
    </ul>`,
    //templateUrl: '/Home/Index',
    providers: [InventoryService]
})
export class AppComponent implements OnInit {
    products: Product[];

    constructor(private productService: InventoryService) { }

    ngOnInit(): void {
        this.productService.getAll()
            .then(products => this.products = products);
    }
}

服务器端路由(RouteConfig.cs):

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

Angular的主页是MVC的共享_Layout.cshtml文件:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

    <!-- 1. Load libraries -->
    <!-- Polyfill(s) for older browsers -->

    <script src="~/node_modules/core-js/client/shim.min.js"></script>
    <script src="~/node_modules/zone.js/dist/zone.js"></script>
    <script src="~/node_modules/systemjs/dist/system.src.js"></script>

    <!-- 2. Configure SystemJS -->
    <script src="~/Scripts/systemjs.config.js"></script>
    <script>
        System.import('../Scripts/main').catch(function (err)
        {
            console.error(err);
        });
    </script>
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

可以直接访问web api控制器(ProductController.cs)并获得有效的JSON输出。

[Route("api/Product/GetProducts")]
        public IEnumerable<ProductJSON> GetProducts()
        {
            IQueryable<ProductJSON> products = _context.Products.Select(
                    p => new ProductJSON
                    {
                        Name = p.Name,
                        Category = p.Category,
                        Price = p.Price
                    });
            return products.ToList();
        }

HomeController.cs如下: -

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }

Index.cshtml如下: -

@{
    ViewBag.Title = "Home Page";
}

<my-app>Loading...</my-app>

使用“模板”时,我可以成功访问“/ Home / Index”路径,但应用程序挂起,无法使用“templateUrl”进行访问

@Component({
    selector: 'my-app',
    template: `<ul>
        <li *ngFor="let product of products">
            <h4>{{product.getProducts()}}</h4>
        </li>
    </ul>`,
    //templateUrl: '/Home/Index',
    providers: [InventoryService]
}) 

1 个答案:

答案 0 :(得分:0)

在混合ASP.NET MVC5和Angular时需要一些不同的方法,您需要将Root组件路径和ASP.NET默认路径分开。

尝试以下,

创建一个新的控制器,让我们说 ComponentsController ,如下所示,

public class ComponentsController : Controller
    {
        // GET: Components
        public ActionResult App()
        {
            return View();
        }
 }

并添加Components\App.cshtml,确保不使用共享的_Layout。

     <ul>
        <li *ngFor="let product of products">
            <h4>{{product.getProducts()}}</h4>
        </li>
    </ul>

更新AppComponent模板网址,以便它使用新路径

templateUrl: '/Components/App' 

删除Index.cshtml的共享布局并直接从Index.cshtml提供,根据您的项目结构修复路径

它应该有用。

使用基本应用程序检查此Github Repo

希望这会有所帮助!!