Angular45
Angular 4 Tutorial for Beginners: Learn Angular 4 from Scratch https://www.youtube.com/watch?v=k5E2AVpwsko&list=PLTjRvDozrdlxAhsPP4ZYtt3G8KbJ449oT 安装Angular CLI: npm install -g @angular/cli 安装之后输入ng --version检查版本. 创建新项目: ng new hello-world 打开vs code, 快捷键ctrol+shift+p,输入code选择Shell Command:Install 'code' command in PATH, 输入code .(code后面空格然后是点) ng server 启动项目 安装typescript: npm install -g typescript javascript中var声明的变量在它所属最近的方法中都有效.e.g. function doSomething(){ for(var i=0;i<5;i++){ console.log(i); } console.log('Finally: '+i); //注意这里的i也是有效的, 如果用typescript中的let定义变量i,则这里的i无效. } 强类型转换: let endsWithC=(<string>message).endsWith('c'); let endsWithC=(message as string).endsWith('c'); typescript中方法的写法: let doLog=(message) => {console.log(message);} 类似于c#中的lamda写法. typescript不能含有多个构造函数, 如果需要实例化不带参数的对象,则设置参数为nullable.e.g. constructor(x?: number, y?: number){ this.x=x; this.y=y; } 上面的写法在typescript中可以简化为: constructor(public x?:number, private y?:number){ } 变量前可以加private,public, protected修饰, 默认的是public. 属性的例子: 变量x是私有的, get X(){ return this.x; } set X(value){ if(value<0) throw new Error(''value cannot be less than 0.); this.x=value; } 使用: let x=point.X; point.X=10; 取名: course-4.component.ts -------------------------------------------------------------------------------------------------------------------------------------------------------- Angular 4 - The Basics (Udemy Course Excerpt) https://www.youtube.com/watch?v=htPYk6QxacQ 安装Bootstrap命令: npm install --save bootstrap 打开.angular-cli.json文件,在"style"节点下添加"../node_modules/bootstrap/dist/css/bootstrap.min.css" selector:'app-servers' //元素 selector:'[app-servers]' //属性 selector:'.app-servers' //类,不支持id TODO: 1:10:0 ----------------------------------------------------------------------------------------------------------------------------------------------------- Angular 5 Tutorial - 1 - Introduction https://www.youtube.com/watch?v=0eWrpsCLMJQ&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ version 1.2.3 各数字分别表示 Major, Minor, Fix(Patch) 检查版本:node -v, npm -v, ng -v(angular cli的版本) AngularCLI官网: https:cli.angular.io 安装命令:npm install -g @angular/cli Angular 5 Tutorial - 3 - Hello World App https://www.youtube.com/watch?v=mDoHtD1hI3I&index=3&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ ng new hello-world --routing cd hello-world ng serve = npm start selector的三种方式: 'app-test','.app-test','[app-test]', 对应的html为<app-test></app-test>,<div class="app-test"></div>,<div app-test></div> Angular 5 Tutorial - 6 - Property Binding https://www.youtube.com/watch?v=N8FBmB2jme8&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=6 Attribute vs Property Attribute - HTML Properties - DOM (Document Object Model) Attribute的值不变, Property的值可变. Property Binding: [disabled]="isDisabled" //1.左侧是[],2.右侧"",3.isDisabled是bool类型. 也可以写成:bind-disabled="isDisabled" [class.text-danger]="hasError" //如果hasError为true则应用样式text-danger,否者不用 多条件: <h2 [ngClass]="messageClasses">Something</h2> //1.[ngClass] 2.messageClassess属性包括多个条件 <h2 [style.color]="highlightColor">Style Binding</h2> //highlightColor是Property <h2 [style.color]="'red'">Style Binding</h2> //'red' <h2 [style.color]="hasError ? 'red' : 'gree'">Style Binding</h2> 多条件: <h2 [ngStyle]="titleStyles">Style Binding 3</h2> //titleStyles里面有多个样式设定 Angular 5 Tutorial - 9 https://www.youtube.com/watch?v=ZfIc1_oj7uM&index=9&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ (click) = "onClick($event)" //带event参数 (click) = "greeting='Hello World'" //直接执行 <input #myInput type="text"> <button (click)="logMessage(myInput.value)">Log</button> 双向绑定需要在app.module.ts中导入FormsModule [(ngModel)]="name" *ngIf="isVisible" //不会显示dom元素 Angular中的if else: 方法一: <h2 *ngIf="displayName; else elseBlock"> Codevolution </h2> <ng-template #elseBlock> <h2> Name is hidden </h2> </ng-template> 方法二: <div *ngIf="displayName; then thenBlock; else elseBlock"></div> <ng-template #thenBlock> <h2>aaa</h2> </ng-template> <ng-template #elseBlock> <h2>bbb</h2> </ng-template> Angular中的Switch: <div [ngSwitch]="color"> <div *ngSwitchCase="'red'">You picked red color</div> <div *ngSwitchCase="'blue'">You picked blue color</div> <div *ngSwitchCase="'green'">You picked green color</div> <div *ngSwitchDefault>Pick again</div> </div> Angular中的for: <div *ngFor="let color of colors; index as i"> <h2>{{i}} {{color}}</h2> </div> Angular 5 Tutorial - 15 - Component Interaction https://www.youtube.com/watch?v=BGy8DdGw_WE&list=TLGG0JkcZDBvWZcxODEyMjAxNw Parent > Child app.component.html: <app-test [parentData]="name"></app-test> test.component.ts: import {Input} from '@angular/core'; //导入命令空间Input @Input() public parentData; //@Input修饰符表示这个属性是从父控件传过来的, 别名的写法: @Input('parentData') public name; Parent > Child test.component.ts: import {Output,EventEmitter} from '@angular/core'; //导入命令空间 @Output() public childEvent = new EventEmitter(); <button (click)="fireEvent()">Send Event</button> fireEvent(){ this.childEvent.emit('Hello World'); } app.component.html: <app-test (childEvent)="message=$event"></app-test> //这里的$event就是子组件中传过来的值'Hello World' Angular 5 Tutorial - 16 - Pipes https://www.youtube.com/watch?v=y8lwG8IM82k&index=2&list=TLGG0JkcZDBvWZcxODEyMjAxNw {{name | slice:3:5}} //显示从第三个字符开始到第五个字符(不包括)之间的字符 {{person | json}} {{5.678 | number:'3.1-2'}} //3表示小数点的左边显示三位数,1-2表示小数点的右边显示最少一位最多两位数,最后显示005.67 {{0.25 | currency}} //显示$0.25 {{0.25 | currency: 'GBP'}} //显示英镑 {{date | date:'short'}} {{date | date:'shortDate'}} {{date | date:'shortTime'}} Angular 5 Tutorial - 21 - Fetch Data Using HTTP https://www.youtube.com/watch?v=LmIsbzt-S_E&index=21&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ ng g s employee 创建employee.service.ts app.module.ts: import {HttpClientModule} from '@angular/common/http'; //Angular5使用HttpClient而不是之前的Http imports:[HttpClientModule] employee.service.ts: import {HttpClient} from '@angular/common/http'; constructor(private http:HttpClient){} getEmployees():Observable<IEmployee[]>{ //需要指定返回结果为Observable<IEmployee[]> return this.http.get<IEmployee[]>(this._url); } Angular 5 Tutorial - 22 - HTTP Error Handling https://www.youtube.com/watch?v=TmTGQiLBS5A&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=22 import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; getEmployees():Observable<IEmployee[]>{ return this.http.get<IEmployee[]>(this._url) .catch(this.errorHandler); } errorHandler(error: HttpErrorResponse){ return Observable.throw(error.message || "Server Error"); } 使用: this._employeeService.getEmployees().subscribe(data=>this.employees=data, error=>this.errorMsg=error); Angular 5 Tutorial - 23 - Routing and Navigation https://www.youtube.com/watch?v=Nehk4tBxD4o&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=23 ng new routing-demo --routing //创建带router的项目 如何在现有项目中添加router: src/index.html: <base href="/"> 添加app/app-routing.module.ts文件,导入到app.module.ts中. ng g c department-list -it -is //创建component 配置app-routing.module.ts: export const routingComponents = [DepartmentListComponent, EmployeeListComponent], 导入到app.module.ts中. 之后有新的components只需要添加到app-routing.module.ts文件中. <a routerLink="/departments" routerLinkActive="active">Departments</a> <a routerLink="/employees" routerLinkActive="active">Employees</a> npm start 启动项目, 打开localhost:4200 Angular 5 Tutorial - 24 - Wildcard Route and Redirecting Routes https://www.youtube.com/watch?v=QC6wRxXT26I&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=24 ng g c page-not-found -it -is //创建component app-routing.module.ts中添加: {path:'', redirectTo:'/departments', pathMatch:'full'} //放在最前,对应地址localhost:4200 {path:"**", component: PageNotFoundComponent} //page not found必须放在最后 Angular 5 Tutorial - 25 - Route Parameters https://www.youtube.com/watch?v=qh5nHv-4aw0&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=26 页面跳转, app-routing.module.ts: import {DepartmentDetailComponent} from './department-detail/department-detail.component'; const routes:Routes=[ {path:'department/:id',component:DepartmentDetailComponent} ]; export const routingComponents=[DepartmentDetailComponent] department-list.component.ts: import {Router} from '@angular/router'; constructor(private router: Router){} onSelect(department){ this.router.navigate(['/departments',department.id]); } 读取url中传过来的参数. department-detail.component.ts: import {ActivatedRoute} from '@angular/router'; constructor(private route: ActivatedRoute){} ngOnInit(){ let id = parseInt(this.route.snapshot.paramMap.get('id')); this.departmentId = id; } Angular 5 Tutorial - 26 - paramMap Observable https://www.youtube.com/watch?v=KRV9jZwl0Ig&index=25&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ route.snapshot有个缺点,当跳转到同一个component只是参数有变化的时候,页面里面获取的参数值不会改变. 这时需要使用route.paramMap来监视参数的变化: import {ParamMap} from 'angular/router'; ngOnInit(){ //let id = parseInt(this.route.snapshot.paramMap.get('id')); //this.departmentId = id; this.route.paramMap.subscribe((params:ParamMap)=>{ let id = parseInt(params.get('id')); this.departmentId = id; }); } Angular 5 Tutorial - 27 - Optional Route Parameters https://www.youtube.com/watch?v=gnTFkl2AF-w&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=27 用于跳转回原地址,回到参数所代表的tab等 gotoDepartments(){ let selectedId = this.departmentId ? this.departmentId : null; this.router.navigate(['/departments',{id: selectedId}]); //点击返回按钮跳转到地址 localhost:4200/departments;id=1, 这里的;id=1即是可选参数 } 读取可选参数id的值: import {Router,ActivatedRoute,ParamMap} from '@angular/router'; constructor(private router: Router, private route: ActivatedRoute){} public selectedId; ngOnInit(){ this.route.paramMap.subscribe(()=>{ let id = parseInt(params.get('id')); this.selectedId=id; }); } Angular 5 Tutorial - 28 - Relative Navigation https://www.youtube.com/watch?v=qktmk-7Kot8&index=28&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ this.router.navigate(['/departments', department.id]); //绝对路径 this.router.navigate([department.id],{relativeTo: this.route}); //相对路径的写法,department-list.component.ts中 this.router.navigate(['../',{id:selectedId}],{relativeTo: this.route}); //department-detail.components.ts中 Angular 5 Tutorial - 29 - Child Routes https://www.youtube.com/watch?v=ZoeZxpfTCXk&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=29 //看完等更新 app-routing.module.ts: { path:'departments/:id', component:DepartmentDetailComponent, children:[ {path:'overview', component: DepartmentOverviewComponent}, {path:'contact', component: DepartmentContactComponent} ] } //添加到routingComponents数组中 export const routingComponents = [DepartmentOverviewComponent,DepartmentContactComponent] department-detail.component.ts: <p> <button (click)="showOverview()">Overview</button> <button (click)="showContact()">Contact</button> </p> <router-outlet></router-outlet> showOverview(){ this.router.navigate(['overview'],{relativeTo: this.route}); } showContact(){ this.router.navigate(['contact'],{relativeTo: this.route}); } ----------------------------------------------------------------------------------------------------------------------------------------------------- Deploy An Angular App To Firebase In Minutes https://www.youtube.com/watch?v=mF7FTWHS3ys 用windows自带的命令窗口,不要用Gitbash. 打开firebase console页面: https://console.firebase.google.com/ 点击项目 > Hosting > Get started...... Javascript中的闭包: Javascript语言的特殊之处,就在于函数内部可以直接读取全局变量。 另一方面,在函数外部自然无法读取函数内的局部变量。 这里有一个地方需要注意,函数内部声明变量的时候,一定要使用var命令。如果不用的话,你实际上声明了一个全局变量! 如何从外部读取局部变量?那就是在函数的内部,再定义一个函数。 函数带()才是执行函数! 由于在Javascript语言中,只有函数内部的子函数才能读取局部变量,因此可以把闭包简单理解成“定义在一个函数内部的函数”。 闭包可以用在许多地方。它的最大用处有两个,一个是前面提到的可以读取函数内部的变量,另一个就是让这些变量的值始终保持在内存中。 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Use Babel & Webpack To Compile ES2015 - ES2017 https://www.youtube.com/watch?v=iWUR04B42Hc babel_webpack_starter: https://github.com/bradtraversy/babel_webpack_starter webpack: https://webpack.github.io/docs/what-is-webpack.html Babel: https://babeljs.io npm init //创建package.json文件,scripts下添加"build":"webpack", "start":"webpack-dev-server --output-public-path=/build/" npm install --save-dev webpack webpack-dev-server babel-core babel-loader babel-preset-env 创建webpack.config.js npm run build //编译 npm start //启动webpack-dev-server就不需要执行npm run build了, 它会一直监视修改不需要刷新页面. 异步方法: async function getPosts(){ const response=await fetch('https://jsonplaceholder.typicode.com/posts'); const data=await response.json(); return data; } getPosts().then(posts=>console.log(posts)); npm install --save-dev babel-polyfill babel-preset-stage-0 修改webpack.config.js -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 01 Blank App In Visual Studio 2017 https://www.youtube.com/watch?v=2VIVOJsKrTI&list=PL2yYLRgebbHakhdiCZkykZQU0CQer3pvO 创建Empty的asp.net core项目, NuGet安装Microsoft.AspNetCore.StaticFiles 安装WebPack Task Runner 网址https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebPackTaskRunner, 打开 Task Runner Explorer 面板. Add New Item > npm Configuration File 创建package.json并修改 Visual Studio的命令窗口是Pacage Manager Console. package.json文件右键选择Restore Packages,相当于执行命令npm install Add New Item > TypeScript JSON Configuration File 创建 tsconfig.json文件并修改 Add New Item > WebPack Configuration File 创建 webpack.config.js文件并修改 index.ts文件中export所有的component和module. import * as Barrel from '*'; //导入index.ts 执行AngularCLI命令编译Angular程序: npm build 在开发的过程中,我们会用到AngularCLI命令中的 ng serve 命令来启用Angular的监控服务模式。他会监控Angular的源码变化,当源码被改变时,自动重新编译Angular程序并编译TypeScript代码。默认情况下ng serve提供的是localhost:4200地址。 ----------------------------------------------------------------------------------------------------------------------------------------------------- Angular 4 CRUD With Web API https://www.youtube.com/watch?v=Ous6v0r7kXc Add New Item > 左侧Data下的ADO.NET Entity Data Model取名DBModels Add Controller > Web API 2 Controller with actions, useing Entity Framework //仔细看下生成的代码,很有借鉴性. 后台Post方法中不需要if(!ModelState.IsValid),所有的验证在angular中. ng new angularCURD //创建angular项目 cd angularCURD ng serve --open //启动服务并打开浏览器localhost://4200 生成的.spec.ts文件是用于测试的,可以删除. ng g class employee.model 生成employee.model.ts文件. app-emplloyees按下tab键,生成<app-emplloyees></app-emplloyees> h2.jumbotron.bg-secondary.text-white按下tab键,生成<h2 class="jumbotron bg-secondary text-white"></h2> //多个class之间用. <input class="form-control" name="Office" #Office="ngModel" [(ngModel)]="employee" /> //#Office="ngModel"用于验证 解决webapi跨域访问的问题: 安装组件Microsoft.AspNet.WebApi.Cors, 地址 https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors ,命令是Install-Package Microsoft.AspNet.WebApi.Cors -Version 5.2.3 (或者Install-Package Microsoft.AspNet.WebApi.Cors) 之后代码: using System.Web.Http.Cors; [EnableCors(origins: "http://localhost:4200",headers:"*",methods:"*")] //加到public class EmployeeControler: ApiController之上 上面是针对指定controller, 加到WebApiConfig.cs文件的Register方法下可以针对整个项目有效. 页面报错的话执行代码Install-Package Microsoft.AspNet.WebApi.Core -Version 5.2.3 安装toastr插件: npm install ngx-toastr --save, 地址https://www.npmjs.com/package/ngx-toastr, .angular-cli.json中的"styles"节点下添加"../node_modules/ngx-toastr/toastr.css" app.modules.ts中: import {ToastrModule} from 'ngx-toastr'; imports:[ ToastrModule.forRoot() ] emplloyees.component.ts中: import {ToastrService} from 'ngx-toastr' constructor(private toastr:ToastrService) this.toastr.success('New Record Added Successfully','Employee Register') showForEdit(emp: Employee) { this.employeeService.selectedEmployee = Object.assign({},emp); } ----------------------------------------------------------------------------------------------------------------------------------------------------- Angular And Contentful - Content Management For Single-Page Web Apps https://www.youtube.com/watch?v=KhmjLjvlmyQ Contentful官网: https://www.contentful.com