Angular 2
Configuration de l'application ASP.net Core pour qu'elle fonctionne avec Angular 2 et TypeScript
Recherche…
Introduction
SCENARIO: Fond Core ASP.NET Angular 2 Composants Angular 2 Front-End utilisant les contrôleurs Asp.net Core
Cela permet d'implémenter Angular 2 sur l'application Asp.Net Core. Il nous permet également d'appeler les contrôleurs MVC à partir de composants Angular 2 avec le résultat MVC View Support Angular 2.
Asp.Net Core + Angular2 + Gulp
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using CoreAngular000.Data;
using CoreAngular000.Models;
using CoreAngular000.Services;
using Microsoft.Extensions.FileProviders;
using System.IO;
namespace CoreAngular000
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange:
true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional:
true);
if (env.IsDevelopment())
{
builder.AddUserSecrets<Startup>();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new
PhysicalFileProvider(Path.Combine(env.ContentRootPath, "node_modules")),
RequestPath = "/node_modules"
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
tsConfig.json
{
"compilerOptions": {
"diagnostics": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"listFiles": true,
"module": "commonjs",
"moduleResolution": "node",
"noImplicitAny": true,
"outDir": "wwwroot",
"removeComments": false,
"rootDir": "wwwroot",
"sourceMap": true,
"suppressImplicitAnyIndexErrors": true,
"target": "es5"
},
"exclude": [
"node_modules",
"wwwroot/lib/"
]
}
Package.json
{
"name": "angular dependencies and web dev package",
"version": "1.0.0",
"description": "Angular 2 MVC. Samuel Maícas Template",
"scripts": {},
"dependencies": {
"@angular/common": "~2.4.0",
"@angular/compiler": "~2.4.0",
"@angular/core": "~2.4.0",
"@angular/forms": "~2.4.0",
"@angular/http": "~2.4.0",
"@angular/platform-browser": "~2.4.0",
"@angular/platform-browser-dynamic": "~2.4.0",
"@angular/router": "~3.4.0",
"angular-in-memory-web-api": "~0.2.4",
"systemjs": "0.19.40",
"core-js": "^2.4.1",
"rxjs": "5.0.1",
"zone.js": "^0.7.4"
},
"devDependencies": {
"del": "^2.2.2",
"gulp": "^3.9.1",
"gulp-concat": "^2.6.1",
"gulp-cssmin": "^0.1.7",
"gulp-htmlmin": "^3.0.0",
"gulp-uglify": "^2.1.2",
"merge-stream": "^1.0.1",
"tslint": "^3.15.1",
"typescript": "~2.0.10"
},
"repository": {}
}
bundleconfig.json
[
{
"outputFileName": "wwwroot/css/site.min.css",
"inputFiles": [
"wwwroot/css/site.css"
]
},
{
"outputFileName": "wwwroot/js/site.min.js",
"inputFiles": [
"wwwroot/js/site.js"
],
"minify": {
"enabled": true,
"renameLocals": true
},
"sourceMap": false
}
]
Convertissez bundleconfig.json en gulpfile (RightClick bundleconfig.json sur l'explorateur de solutions, Bundler & Minifier> Convert to Gulp
Vues / Accueil / Index.cshtml
@{
ViewData["Title"] = "Home Page";
}
<div>{{ nombre }}</div>
Pour le dossier wwwroot, utilisez https://github.com/angular/quickstart seed. Vous avez besoin de: index.html main.ts, systemjs-angular-loader.js, systemjs.config.js, tsconfig.json et le dossier app
wwwroot / Index.html
<html>
<head>
<title>SMTemplate Angular2 & ASP.NET Core</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<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>
<script src="systemjs.config.js"></script>
<script>
System.import('main.js').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading AppComponent here ...</my-app>
</body>
</html>
Vous pouvez appeler comme cela pour les contrôleurs à partir de templateUrl. wwwroot / app / app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: '/home/index',
})
export class AppComponent { nombre = 'Samuel Maícas'; }
[Graine] Asp.Net Core + Angular2 + Gulp sur Visual Studio 2017
- Télécharger la graine
- Exécuter la restauration dotnet
- Exécutez npm install
Toujours. Prendre plaisir.
https://github.com/SamML/CoreAngular000
MVC <-> Angular 2
Comment: APPELER ANGULAIRE 2 COMPOSANTES HTML / JS À PARTIR DU CONTRÔLEUR ASP.NET Core:
Nous appelons le HTML à la place de retour Voir ()
return File("~/html/About.html", "text/html");
Et charger la composante angulaire dans le HTML. Ici, nous pouvons décider si nous voulons travailler avec un module identique ou différent. Dépend de la situation
wwwroot / html / About.html
<!DOCTYPE html>
<html>
<head>
<title>About Page</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../css/site.min.css" rel="stylesheet" type="text/css"/>
<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>
<script src="../systemjs.config.js"></script>
<script>
System.import('../main.js').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<aboutpage>Loading AppComponent here ...</aboutpage>
</body>
</html>
(*) Cette graine doit déjà charger la liste complète des ressources
Comment: APPELER ASP.NET Core Controller pour afficher une vue MVC avec prise en charge Angular2:
import { Component } from '@angular/core';
@Component({
selector: 'aboutpage',
templateUrl: '/home/about',
})
export class AboutComponent {
}