Vous êtes sur la page 1sur 30

Môi Trường

tsconfig.json is the TypeScript compiler configuration.

"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.

 core-js: It brings ES2015/ES6 capabilities to our ES5 browsers.

 jasmine: It is the typing for Jasmine test framework.

 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"

package.json will contain the packages that our apps require.

"name": "angular2-demo",

"version": "1.0.0",

"scripts": {

"start": "concurrent ¥"npm run tsc:w¥" ¥"npm run lite¥" ",

"tsc": "tsc",

"tsc:w": "tsc -w",

"lite": "lite-server",

"typings": "typings",

"postinstall": "typings install"


},

"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"

Để cài đặt thì sử dụng

npm install

Lưu ý: cài đặt và cấu hình nodejs trước khi chạy

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.

Some of the applications will have a component class name


as AppComponent and you can find it in a file called app.component.ts.
Use the export statement to export component class from module as
shown below:

export class AppComponent { }

The export statement specifies that it is a module and


its AppComponent class is defined as public and can be accessible to
other modules of the application.

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.

To register component, we use @Component annotation and can be


used to break up the application into smaller parts. There will be only
one component per DOM element.

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',

template : '<h2>Name is Harry</h2>'

directives : [MyComponentDetails]

})

export class ListComponent{...}

The @Component is a decorator which uses configuration object to


create the component and its view. The selector creates an instance
of the component where it finds <mylist> tag in parent HTML.
The template tells Angular how to display the component.
The directive decorator is used to represent the array of components
or directives.

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:

 Interpolation: It displays the component value within the div tags.

 Property Binding: It passes the property from the parent to property of


the child.

 Event Binding: It fires when you click on the components method name.

 Two-way Binding: This form binds property and event by using


the ngModel directive in a single notation.

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:

 Component Directive: It creates custom controller by using view and


controller and used as custom HTML element.

 Decorator Directive: It decorates the elements using additional


behavior.

 Template Directive: It converts HTML into a reusable template.

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.

You must remember the below points while using Dependency


Injection:

 The Dependency Injection is stimulated into the framework and can be


used everywhere.

 The injector mechanism maintains service instance and can be created


using a provider.

 The provider is a way of creating a service.

 You can register the providers along with injectors.

Đọc kỹ hơn tại link:

https://www.tutorialspoint.com/angular2/angular2_architecture.htm

Hướng dẫn cách dùng MVC 6 và AngularJS2 với .NET Core

Đầ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

Giờ thì chúng ta hãy nghiên cứu từng file một.

Initial Template
Từ Solution Explorer
Trước hết, chúng ta cần biết về file Program.cs
namespace CoreMVCAngular

public class Program

public static void Main(string[] args)

var host = new WebHostBuilder()

.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

public class Startup

// This method gets called by the runtime. Use this method to add services

to the container.

// For more information on how to configure your application, visit

http://go.microsoft.com/fwlink/?LinkID=398940

public void ConfigureServices(IServiceCollection services)

// This method gets called by the runtime. Use this method to configure the

HTTP request

pipeline.

public void Configure(IApplicationBuilder app, IHostingEnvironment env,

ILoggerFactory

loggerFactory)

loggerFactory.AddConsole();

if (env.IsDevelopment())
{

app.UseDeveloperExceptionPage();

app.Run(async (context) =>

await context.Response.WriteAsync("Hello World!");

});

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.

Ở đây, đoạn mã được thay đổi.

"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"

Nhấp vào Lưu.

Nó sẽ bắt đầu khôi phục lại các gói tự động.

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?}");
});
}

Trong phương thức ConfigureServices, cần thêm framework Service. Thêm


services.AddMvc();
public void ConfigureServices(IServiceCollection services) {

services.AddMvc();

Cấu trúc thư mục MVC

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

1. Quản lý phụ thuộc Client-side


2. Sử dụng Package Manager (NPM).
3. Sử dụng Task Runner.
4. Bootstrap sử dụng Type Script.

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";

var gulp = require("gulp");


var root_path = { webroot: "./wwwroot/" };

//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/'));
});

gulp.task("copy-all", ["copy-rxjs", 'copy-angular2', 'copy-systemjs', 'copy-es6-


shim']);

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.

Chạy & kết thúc.

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'".

Bootstrapping with TypeScript


tsConfig.json

{
"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.

import {bootstrap} from 'angular2/platform/browser';


import {AppComponent} from './app.component';
import {enableProdMode} from 'angular2/core';

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.

import {Component} từ 'angular2/core';

@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>

</html> Index.cshtml @{ ViewData["Title"] = "Home Page"; }


<core-app>
<div>
<p><img src="~/img/ajax_small.gif" /> Please wait ...</p>
</div>
</core-app> @section Scripts {
<script>
System.config({
packages: {
'app': {
defaultExtension: 'js'
}
},
});
System.import('app/main').then(null, console.error.bind(console));
</script> }

Vous aimerez peut-être aussi