Académique Documents
Professionnel Documents
Culture Documents
"compilerOptions": {
"target": "es5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules",
"typings/main",
"typings/main.d.ts"
}
typings.json file is used to identify TypeScript definition files in your
Angular application.
node: It is used for the code that references objects in the nodejs
environment.
"globalDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160602141332",
"jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
"node": "registry:dt/node#6.0.0+20160621231320"
"name": "angular2-demo",
"version": "1.0.0",
"scripts": {
"tsc": "tsc",
"lite": "lite-server",
"typings": "typings",
"license": "ISC",
"dependencies": {
"angular2": "2.0.0",
"systemjs": "0.19.22",
"es6-promise": "^3.0.2",
"es6-shim": "^0.33.3",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.2",
"zone.js": "0.5.15"
},
"devDependencies": {
"concurrently": "^2.0.0",
"lite-server": "^2.1.0",
"typescript": "^1.7.5",
"typings":"^0.6.8"
npm install
Architecture
Module
Component
Template
Metadata
Data Binding
Service
Directive
Dependency Injection
Module
The module component is characterized by a block of code which can
be used to perform a single task. You can export the value of
something from the code such as a class. The Angular apps are called
as modules and build your application using many modules. The basic
building block of Angular 2 is a component class which can be
exported from a module.
Component
A component is a controller class with a template which mainly deals
with a view of the application and logic on the page. It is a bit of code
that can be used throughout an application. Component knows how to
render itself and configure dependency injection. You can associate
CSS styles using component inline styles, style urls and template
inline styles to a component.
Template
The component's view can be defined by using the template which
tells Angular how to display the component. For instance, below
simple template shows how to display the name:
<div>
Your name is : {{name}}
</div>
To display the value, you can put template expression within the
interpolation braces.
Metadata
Metadata is a way of processing the class. Consider we have one
component called MyComponent which will be a class until we tell
Angular that it's a component. You can use metadata to the class to
tell Angular that MyComponent is a component. The metadata can be
attached to TypeScript by using the decorator.
For instance:
@Component({
selector : 'mylist',
directives : [MyComponentDetails]
})
Data Binding
Data binding is a process of coordinating application data values by
declaring bindings between sources and target HTML elements. It
combines the template parts with components parts and template
HTML is bound with markup to connect both sides. There are four
types of data binding:
Event Binding: It fires when you click on the components method name.
Service
Services are JavaScript functions that are responsible for doing a
specific task only. Angular services are injected using Dependency
Injection mechanism. Service includes the value, function or feature
which is required by the application. Generally, service is a class which
can perform something specific such as logging service, data service,
message service, the configuration of application etc. There is nothing
much about service in Angular and there is no ServiceBase class, but
still services can be treated as fundamental to Angular application.
Directive
The directive is a class that represents the metadata. There are three
types of directives:
Dependency Injection
Dependency Injection is a design pattern that passes an object as
dependencies in different components across the application. It
creates new a instance of class along with its required dependencies.
https://www.tutorialspoint.com/angular2/angular2_architecture.htm
Đầu tiên tạo một project mới Visual Studio 2015 > File > New > Project
Chọn cho mình template và click Ok
Visual Studio sẽ tạo project ASP.NET Core Empty
Initial Template
Từ Solution Explorer
Trước hết, chúng ta cần biết về file Program.cs
namespace CoreMVCAngular
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
.UseKestrel(): Xác định Web Server. ASP.NET Core hỗ trợ việc lưu trữ trong IIS và IIS
Express
HTTP servers
1. Microsoft.AspNetCore.Server.Kestrel (cross-platform)
2. Microsoft.AspNetCore.Server.WebListener (Windows-only)
.UseContentRoot(Directory.GetCurrentDirectory()): Đường dẫn Application base
path chỉ đến thư mục gốc của Application.
.UseIISIntegration(): Dành cho lưu trữ trong IIS và IIS Express.
.UseStartup<Startup>(): Chỉ định lớp Startup.
.Build() : Build IWebHost, tổ chức ứng dụng và quản lý các request HTTP.
Startup.cs
Đây là điểm mấu chốt của ứng dụng .Net Core Application. Nó cung cấp các dịch vụ,
các ứng dụng cần thiết.
namespace CoreMVC
// This method gets called by the runtime. Use this method to add services
to the container.
http://go.microsoft.com/fwlink/?LinkID=398940
// This method gets called by the runtime. Use this method to configure the
HTTP request
pipeline.
ILoggerFactory
loggerFactory)
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
});
Như bạn thấy, có hai phương thức; ConfigureServices và Configure. Trong phương
thức Configure, ba tham số được xác định.
IApplicationBuilder định nghĩa một lớp, trong đó cung cấp các cơ chế để cấu hình
request của ứng dụng.
Chúng ta có thể thêm MVC (middleware) để request kênh liên lạc bằng cách sử dụng
phương thức mớ rộng "Use". Sau đó, sử dụng nó.
ConfigureServices là một phương thức mở rộng, được cấu hình để sử dụng một số
dịch vụ.
Project.json: Đây là nơi phụ thuộc ứng dụng được liệt kê, tức là theo tên và phiên
bản. Tập tin này cũng quản lý runtime, thiết lập trình biên dịch.
Dependencies: Tất cả ứng dụng Dependencies có thể thêm phụ thuộc mới, nếu cần
thiết, IntelliSense sẽ giúp đỡ bao gồm có tên và phiên bản
Sau khi lưu thay đổi, nó sẽ tự động khôi phục lại phụ thuộc từ NuGet.
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.0",
"type": "platform"
},
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.0"
},
Để gỡ bỏ cài đặt, đi đến Solution explorer > click chuột phải vào package > Chọn
Uninstall package.
Công cụ: phần này quản lý và các dòng lệnh. Chúng ta có thể thấy IISIntegration.
Công cụ được thêm vào mặc định, chứa dotnet publish iis command cho xuất bản các
ứng dụng trên IIS.
"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
},
Frameworks: Bước đầu ứng dụng đang chạy trên nền tảng .NET Core mặc định với
runtime.
"netcoreapp1 .0".
"frameworks": {
"netcoreapp1.0": {
"imports": ["dotnet5.6", "portable-net45+win8"]
}
},
Build Options: Tùy chọn, thông qua trình biên dịch trong khi xây dựng các ứng dụng.
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
},
RuntimeOptions: Quản lý máy chủ garbage collection tại ứng dụng runtime.
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true
}
},
PublishOptions: Xác định file/folder đến include/exclude to/from thư mục ra,
trong khi xuất bản các ứng dụng.
"publishOptions": {
"include": ["wwwroot", "web.config"]
},
Scripts: Scripts là kiểu object , trong đó quy định các Scripts chạy trong building
hoặc publishing ứng dụng.
"scripts": {
"postpublish": ["dotnet publish-iis --publish-folder %publish:OutputPath% --
framework
%publish:FullTargetFramework%"]
}
Thêm MVC6
Đây là lúc để thêm MVC6. Trong .NET Core 1.0 MVC & Web API được hợp nhất, và
trở thành lớp duy nhất, kế thừa từ lớp cơ sở.
Hãy thêm MVC Service cho ứng dụng. Mở project.json để thêm phụ thuộc mới trong
đó. Trong phần phụ thuộc, thêm hai phụ thuộc.
"Microsoft.AspNetCore.Mvc": "1.0.0",
"Microsoft.AspNetCore.StaticFiles": "1.0.0"
Giờ thêm MVC (midleware) để request kênh liên lạc trong phương thức Config ở lớp
startup.
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory
loggerFactory) {
loggerFactory.AddConsole();
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
//app.UseStaticFiles();
app.UseMvc(routes => {
routes.MapRoute(name: "default", template:
"{controller=Home}/{action=Index}/{id?}");
});
}
services.AddMvc();
Hãy thêm cấu trúc thư mục MVC đến ứng dụng mẫu. Thêm các tập tin trong thư mục
views & MVC Controller trong thư mục controller như MVC Application cũ.
Ở đây, bạn có thể có một file mới trong folder Views "_ViewImports.cshtml". Tập tin
này có trách nhiệm thiết lập các namespace, có thể được truy cập bởi views trong
project, mà trước đó đã được thực hiện bởi các tập tin Web.config trong thư mục
views.
Hãy sửa đổi nội dung view với thông điệp chào mừng. Chạy ứng dụng.
Bạn có thể thấy thông báo chào mừng xuất hiện ở trang chủ.
AngularJS
AngularJS2 là framework JavaScript modern Client cuối cho việc phát triển ứng dụng.
Framework JavaScript này là hoàn toàn mới và được viết dựa trên TypeScript.
Chúng ta sẽ thực hiện theo các bước, để học hỏi, làm thế nào cài đặt
Phụ thuộc Client-side: Cần phải thêm một tập tin cấu hình JSON cho Node Package
Manager (NPM).
Nhấp Add > New Item> Client- Side > npm Configuration File và nhấp OK.
Mở tệp tin mới được thêm vào sửa đổi các thiết lập ban đầu.
Package.json
{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"Dependencies": {
"angular2": "2.0.0-beta.9",
"systemjs": "0.19.24",
"es6-shim": "^0.33.3",
"rxjs": "5.0.0-beta.2"
},
"devDependencies": {
"gulp": "3.8.11",
"gulp-concat": "2.5.2",
"gulp-cssmin": "0.1.7",
"gulp-uglify": "1.2.0",
"rimraf": "2.2.8"
}
}
Trong phần phụ thuộc, cần thêm AngularJS2 với phụ thuộc khác:
1. Es6-shim là thư viện, cung cấp khả năng tương thích với môi trường cũ.
2. Rxjs cung cấp nhiều tập tin cấu trúc mô-đun trong một loạt các định dạng.
3. SystemJS cho phép điều hướng các tệp tin System.import TypeScript.
Nhấp lưu. Nó sẽ phục hồi tự động. Ở đây, có tất cả các gói cần thiết trong phần phụ
thuộc.
Trong ứng dụng này, bổ sung thêm package manager khác gọi Bower, Click Add >
New Item> Client- Side > Bower Configuration File sau đó nhấp vào Ok.
Bower:
1. Quản lý thành phần html, css, js
2. Tải các tài nguyên tối thiểu
3. Tải flat dependencies
NPM:
1. Cài đặt dependencies recursively
2. Tải nested dependencies
3. Quản lý mô-đun NodeJS
Mở file config sau đó thêm phụ thuộc cần thiết trong phần phụ thuộc với phiên bản
cụ thể.
Lưu file JSON sau khi chỉnh sửa, nó sẽ tự động khôi phục gói trong project. Ở đây đã
thêm gói jquery & Bootstrap với quản lý gói Bower.
Bây giờ, chúng ta hãy thêm một tập tin cấu hình gulp để chạy các công việc. Nhấn
vào Add> New Item> Client-Side. Chọn tập tin gulpJSON bao gồm.
Gulp.json
/*
This file in the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/
"use strict";
//library source
root_path.nmSrc = "./node_modules/";
//library destination
root_path.package_lib = root_path.webroot + "lib-npm/";
gulp.task("copy-systemjs", function () {
return gulp.src(root_path.nmSrc + '/systemjs/dist/**/*.*', {
base: root_path.nmSrc + '/systemjs/dist/'
}).pipe(gulp.dest(root_path.package_lib + '/systemjs/'));
});
gulp.task("copy-angular2", function () {
return gulp.src(root_path.nmSrc + '/angular2/bundles/**/*.js', {
base: root_path.nmSrc + '/angular2/bundles/'
}).pipe(gulp.dest(root_path.package_lib + '/angular2/'));
});
gulp.task("copy-es6-shim", function () {
return gulp.src(root_path.nmSrc + '/es6-shim/es6-sh*', {
base: root_path.nmSrc + '/es6-shim/'
}).pipe(gulp.dest(root_path.package_lib + '/es6-shim/'));
});
gulp.task("copy-rxjs", function () {
return gulp.src(root_path.nmSrc + '/rxjs/bundles/*.*', {
base: root_path.nmSrc + '/rxjs/bundles/'
}).pipe(gulp.dest(root_path.package_lib + '/rxjs/'));
});
Chạy tác vụ, nhấp chuột phải vào tập tin Gulp.json để tải lại.
Nhấp chuột phải vào copy tất cả & bấm chạy.
Trong Solution Explorer, tất cả các gói cần được sao chép. Cần đặt các định nghĩa
kiểu cho es6-shim (typing folder), không có điều này, nó sẽ gây ra lỗi - "Cannot find
name 'Promise'".
{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
//add this to compile app component
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "system",
"moduleResolution": "node"
},
"exclude": ["node_modules", "wwwroot/lib"]
}
noImplicitAny : Đề xuất một lỗi trên các biểu thức và khai báo với kiểu 'bất
kỳ'.
noEmitOnError : Không phát ra kết quả đầu ra, nếu có sai sót đã được báo
cáo.
Target : Xác định phiên bản đích ECMAScript: 'ES5' (mặc định), 'ES5', hoặc
'es6'.
experimentalDecorators: cho phép thử nghiệm hỗ trợ cho ES7 decorators.
Nhận biết thêm chi tiết về trình biên dịch tùy chọn ở đây .
Tạo một thư mục ứng dụng cho file .ts trong thư mục wwwroot.
Trong Solution Explorer, bạn có thể thêm các tập tin, đưa ra dưới đây.
Trong đoạn mã main.ts, bootstrap AngularJS import các thành phần.
enableProdMode();
bootstrap(AppComponent);
Component: Chèn chức năng Component từ thư viện Angular 2; sử dụng import, lớp
app component có thể được import từ Component khác.
@Component({
selector: 'core-app',
template: '<h3>Welcome to .NET Core 1.0 + MVC6 + Angular 2</h3>'
})
export class AppComponent {}
MVC View
Thêm layout sau
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
<script src="~/lib-npm/es6-shim/es6-shim.js"></script>
<script src="~/lib-npm/angular2/angular2-polyfills.js"></script>
<script src="~/lib-npm/systemjs/system.src.js"></script>
<script src="~/lib-npm/rxjs/Rx.js"></script>
<script src="~/lib-npm/angular2/angular2.js"></script>
</head>
<body>
<div> @RenderBody() </div> @RenderSection("scripts", required: false)
</body>