Saturday, February 11, 2017

The folder structure requirements for Angular 2 in a C# MVC application are a little finicky.

Do not put the Angular stuff in the Scripts folder with all of the other random JS stuff. It needs its own folder at the root of the UI project and this folder cannot just be named anything. The folder needs to be named after the Controller that will cough up a view that uses it! That means in the case of HomeController your Angular app will go in a "Home" folder in the root of your UI project with the "app" and "node_modules" folders immediately inside of it and in the case of WhateverController your Angular app will go in a "Whatever" folder in the root of your UI project with the "app" and "node_modules" folders immediately inside of that folder. It might be best NOT to use the HomeController and to instead make something new honestly. Consider these three URLs:

  1. http://localhost:60892/Home/Index
  2. http://localhost:60892/Home
  3. http://localhost:60892

Alright, the first two will work great with an Angular app in a "Home" folder and the third will barf red up to Google Chrome's console instead of behaving itself. That's frustrating! I hacked around this problem by making the HomeController automatically redirect to a different controller and then using that controller to fish for the view for the Angular 2 mechanics. The Home Controller just looks like this now:

using System.Web.Mvc;
namespace MyApp.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         return RedirectToAction("Index", "Whatever");
      }
   }
}

 
 

In the view that actually summons the .js files for Angular code you should craft URLs like so:

<script src="~/Whatever/node_modules/core-js/client/shim.min.js"></script>

No comments:

Post a Comment