




已阅读5页,还剩13页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Angular4基础知识培训之快速入门目录 第一节 - Angular 简介 第二节 - Angular 环境搭建 第三节 - 插值表达式 第四节 - 自定义组件 第五节 - 常用指令简介 第六节 - 事件绑定 第七节 - 表单模块简介 第八节 - Http 模块简介 第九节 - 注入服务 第十节 - 路由模块简介第一节 Angular 简介Angular 是什么Angular 是由谷歌开发与维护一个开发跨平台应用程序的框架,同时适用于手机与桌面。Angular 有什么特点 基于 Angular 我们可以构建适用于所有平台的应用。比如:Web 应用、移动 Web 应用、移动应用和桌面应用等。 通过 Web Worker和服务端渲染 (SSR),达到在如今Web平台上所能达到的最高渲染速度。 Angular 让你能够有效掌控可伸缩性。基于 RxJS、Immutable.js 和其它推送模型,能适应海量数据需求。Angular 提供了哪些功能 动态HTML 强大的表单系统 (模板驱动和模型驱动) 强大的视图引擎 事件处理 快速的页面渲染 灵活的路由 HTTP 服务 视图封装 AOT、Tree ShakingAngular 与 AngularJS 有什么区别 不再有Controller和Scope 更好的组件化及代码复用 更好的移动端支持 引入了RxJS与Observable 引入了Zone.js,提供更加智能的变化检测第二节 - Angular 环境搭建基础要求 Node.js GitAngular 开发环境配置方式 基于 Angular Quickstarto /angular/quickstart 基于 Angular CLIo npm install -g angular/cli配置开发环境我们选用第一种配置方式搭建 Angular 开发环境:基于 Angular Quickstart 使用Git克隆 quickstart 项目git clone /angular/quickstart ng4-quickstart 使用IDE打开已新建的项目code ./ng4-quickstart 安装项目所需依赖npm i 验证环境是否搭建成功npm start基于 Angular CLI 安装Angular CLI(可选)npm install -g angular/cli 检测 Angular CLI 是否安装成功ng -version 创建新的项目ng new PROJECT-NAME 启动本地服务器cd PROJECT-NAME ng serve第三节 - 插值表达式在 Angular 中,我们可以使用 插值语法实现数据绑定。绑定普通文本import Component from angular/core; Component( selector: my-app, template: Hello name, ) export class AppComponent name = Angular; 绑定对象属性import Component from angular/core; Component( selector: my-app, template: 大家好,我是name 我来自vince省, address.city市 , ) export class AppComponent name = Semlinker; address = province: 福建, city: 厦门 值得一提的是,我们可以使用 Angular 内置的 json 管道,来显示对象信息:Component( selector: my-app, template: . address | json , ) export class AppComponent name = Semlinker; address = province: 福建, city: 厦门 第四节 - 自定义组件在 Angular 中,我们可以通过 Component 装饰器和自定义组件类来创建自定义组件。基础知识定义组件的元信息在 Angular 中,我们可以使用 Component 装饰器来定义组件的元信息:Component( selector: my-app, / 用于定义组件在HTML代码中匹配的标签 template: Hello name, / 定义组件内嵌视图 )定义组件类export class AppComponent name = Angular; 定义数据接口在 TypeScript 中的接口是一个非常灵活的概念,除了可用于对类的一部分行为进行抽象以外,也常用于对对象的形状(Shape)进行描述。interface Person name: string; age: number; let semlinker: Person = name: semlinker, age: 31 ;自定义组件示例创建 UserComponent 组件import Component from angular/core; Component( selector: sl-user, template: 大家好,我是name 我来自vince省, address.city市 ) export class UserComponent name = Semlinker; address = province: 福建, city: 厦门 ; 声明 UserComponent 组件/ . import UserComponent from ./ponent; NgModule( imports: BrowserModule , declarations: AppComponent, UserComponent, bootstrap: AppComponent ) export class AppModule 使用 UserComponent 组件import Component from angular/core; Component( selector: my-app, template: , ) export class AppComponent 使用构造函数初始化数据Component(.) export class UserComponent name: string; address: any; constructor() = Semlinker; this.address = province: 福建, city: 厦门 接口使用示例定义 Address 接口interface Address province: string; city: string; 使用 Address 接口export class UserComponent name: string; address: Address; / . 第五节 - 常用指令简介在 Angular 实际项目中,最常用的指令是 ngIf 和 ngFor 指令。基础知识ngIf 指令简介该指令用于根据表达式的值,动态控制模板内容的显示与隐藏。它与 AngularJS 1.x 中的 ng-if 指令的功能是等价的。ngIf 指令语法.ngFor 指令简介该指令用于基于可迭代对象中的每一项创建相应的模板。它与 AngularJS 1.x 中的 ng-repeat 指令的功能是等价的。ngFor 指令语法.ngIf 与 ngFor 指令使用示例import Component from angular/core; interface Address province: string; city: string; Component( selector: sl-user, template: 大家好,我是name 我来自vince省, address.city市 我的技能 skill ) export class UserComponent name: string; address: Address; showSkills: boolean; skills: string; constructor() = Semlinker; this.address = province: 福建, city: 厦门 ; this.showSkills = true; this.skills = AngularJS 1.x, Angular 2.x, Angular 4.x; 第六节 - 事件绑定在 Angular 中,我们可以通过 (eventName) 的语法,实现事件绑定。基础知识事件绑定语法等价于介绍完事件绑定的语法,接下来我们来为第五节中的 UserComponent 组件,开发一个功能,即可以让用户动态控制技能信息的显示与隐藏。事件绑定示例Component( selector: sl-user, template: . showSkills ? 隐藏技能 : 显示技能 . ) export class UserComponent / . toggleSkills() this.showSkills = !this.showSkills; 第七节 - 表单模块简介Angular 中有两种表单: Template Driven Forms - 模板驱动式表单 (类似于 AngularJS 1.x 中的表单 ) Reactive Forms - 响应式表单本小节主要介绍模板驱动式的表单,接下来我们来演示如何通过表单来为我们的之前创建的 UserComponent 组件,增加让用户自定义技能的功能。基础知识导入表单模块import FormsModule from angular/forms; / . NgModule( imports: BrowserModule, FormsModule, declarations: AppComponent, UserComponent, bootstrap: AppComponent ) export class AppModule 模板变量语法 Pause等价于表单使用示例Component( selector: sl-user, template: . 我的技能 . 添加技能 ) export class UserComponent / . addSkill(skill: string) let skillStr = skill.trim(); if (this.skills.indexOf(skillStr) = -1) this.skills.push(skillStr); 第八节 - Http 模块简介Angular 4.3 版本后,推荐使用 HttpClient基础知识(Angular 4.3 版本前)导入 Http 模块/ . import HttpModule from angular/http; NgModule( imports: BrowserModule, FormsModule, HttpModule, declarations: AppComponent, UserComponent, bootstrap: AppComponent ) export class AppModule 使用 Http 服务步骤(1) 从 angular/http 模块中导入 Http 类(2) 导入 RxJS 中的 map 操作符(3) 使用 DI 方式注入 http 服务(4) 调用 http 服务的 get() 方法,设置请求地址并发送 HTTP 请求(5) 调用 Response 对象的 json() 方法,把响应体转成 JSON 对象(6) 把请求的结果,赋值给对应的属性Http 服务使用示例使用 Http 服务import Component, OnInit from angular/core; import Http from angular/http; / (1) import rxjs/add/operator/map; / (2) interface Member id: string; login: string; avatar_url: string; Component( selector: sl-members, template: Angular Orgs Members ID:member.id Name: member.login ) export class MembersComponent implements OnInit members: Member; constructor(private http: Http) / (3) ngOnInit() this.http.get(/orgs/angular/members?page=1&per_page=5) / (4) .map(res = res.json() / (5) .subscribe(data = if (data) this.members = data; / (6) ); 声明 MembersComponent 组件/ . import MembersComponent from ./ponent; NgModule( imports: BrowserModule, FormsModule, HttpModule, declarations: AppComponent, UserComponent, MembersComponent, bootstrap: AppComponent ) export class AppModule 使用 MembersComponent 组件import Component from angular/core; Component( selector: my-app, template: , ) export class AppComponent 基础知识(Angular 4.3 版本后)HttpClientModule 应用导入新的 HTTP Moduleimport HttpClientModule from angular/common/http; NgModule( declarations: AppComponent , imports: BrowserModule, HttpClientModule , providers: , bootstrap: AppComponent ) export class AppModule 需要注意的是,现在 JSON 是默认的数据格式,我们不需要再进行显式的解析。即我们不需要再使用以下代码:http.get(url).map(res = res.json().subscribe(.)现在我们可以这样写:http.get(url).subscribe(.)发送 Get 请求import Component, OnInit from angular/core; import Observable from rxjs/Observable; import HttpClient from angular/common/http; import * as _ from lodash; interface Course description: string; courseListIcon:string; iconUrl:string; longDescription:string; url:string; Component( selector: app-root, template: course.description No Data Available ) export class AppComponent implements OnInit courses$: Observable; constructor(private http:HttpClient) ngOnInit() this.courses$ = this.http .get(/courses.json) .map(data = _.values(data) .do(console.log); 设置查询参数假设发送 Get 请求时,需要设置对应的查询参数,预期的 URL 地址如下:/courses.json?orderBy=$key&limitToFirst=1创建 HttpParams 对象import HttpParams from angular/common/http; const params = new HttpParams() .set(orderBy, $key) .set(limitToFirst, 1); this.courses$ = this.http .get(/courses.json, params) .do(console.log) .map(data = _.values(data)需要注意的是,我们通过链式语法调用 set() 方法,构建 HttpParams 对象。这是因为 HttpParams 对象是不可变的,通过 set()方法可以防止该对象被修改。每当调用 set() 方法,将会返回包含新值的 HttpParams 对象,因此如果使用下面的方式,将不能正确的设置参数。const params = new HttpParams(); params.set(orderBy, $key) params.set(limitToFirst, 1);使用 fromString 语法const params = new HttpParams(fromString: orderBy=$key&limitToFirst=1);使用 request() APIconst params = new HttpParams(fromString: orderBy=$key&limitToFirst=1); this.courses$ = this.http .request( GET, /courses.json, responseType:json, params ) .do(console.log) .map(data = _.values(data);设置 HTTP Headersconst headers = new HttpHeaders().set(X-CustomHeader, custom header value); this.courses$ = this.http .get( /courses.json, headers) .do(console.log) .map(data = _.values(data);发送 Put 请求httpPutExample() const headers = new HttpHeaders().set(Content-Type, application/json); this.http.put(/courses/-KgVwECOnlc-LHb_B0cQ.json, courseListIcon: ./main-page-logo-small-hat.png, description: Angular Tutorial For Beginners TEST, iconUrl: ./angular2-for-beginners.jpg, longDescription: ., url: new-value-for-url , headers) .subscribe( val = console.log(PUT call successful value returned in body, val); , response = console.log(PUT call in error, response); , () = console.log(The PUT observable is now completed.); ); 发送 Patch 请求httpPatchExample() this.http.patch(/courses/-KgVwECOnlc-LHb_B0cQ.json, description: Angular Tutorial For Beginners PATCH TEST, ) .subscribe( (val) = console.log(PATCH call successful value returned in body, val); , response = console.log(PATCH call in error, response); , () = console.log(The PATCH observable is now completed.); ); 发送 Delete 请求httpDeleteExample() this.http.delete(/courses/-KgVwECOnlc-LHb_B0cQ.json) .subscribe( (val) = console.log(DELETE call successful value returned in body, val); , response = console.log(DELETE call in error, response); , () = console.log(The DELETE observable is now completed.); ); 发送 Post 请求httpPostExample() this.http.post(/courses/-KgVwECOnlc-LHb_B0cQ.json, courseListIcon: ., description: TEST, iconUrl: ., longDescription: ., url: new-url ) .subscribe( (val) = console.log(POST call successful value returned in body, val); , response = console.log(POST call in error, response); , () = console.log(The POST observable is now completed.); ); 避免重复请求duplicateRequestsExample() const httpGet$ = this.http .get(/courses.json) .map(data = _.values(data); httpGet$.subscribe( (val) = console.log(logging GET value, val) ); this.courses$ = httpGet$; 在上面例子中,我们正在创建了一个 HTTP observable 对象 httpGet$,接着我们直接订阅该对象。然后,我们把 httpGet$ 对象赋值给 courses$ 成员变量,最后在模板中使用 async 管道订阅该对象。这将导致发送两个 HTTP 请求,在这种情况下,请求显然是重复的,因为我们只希望从后端查询一次数据。为了避免发送冗余的请求,我们可以使用 RxJS 提供的 shareReplay 操作符:/ put this next to the other RxJs operator imports import rxjs/add/operator/shareReplay; const httpGet$ = this.http .get(/courses.json) .map(data = _.values(data) .shareReplay();并行发送多个请求并行发送 HTTP 请求的一种方法是使用 RxJs 中的 forkjoin 操作符:import rxjs/add/observable/forkJoin; parallelRequests() const parallel$ = Observable.forkJoin( this.http.get(/courses/-KgVwEBq5wbFnjj7O8Fp.json), this.http.get(/courses/-KgVwECOnlc-LHb_B0cQ.json) ); parallel$.subscribe( values = console.log(all values, values) ); 顺序发送 Http 请求sequentialRequests() const sequence$ = this.http.get(/courses/-KgVwEBq5wbFnjj7O8Fp.json) .switchMap(course = course.description+= - TEST ; return this.http.put(/courses/-KgVwEBq5wbFnjj7O8Fp.json, course) ); sequence$.subscribe(); 获取顺序发送 Http 请求的结果sequentialRequests() const sequence$ = this.http.get(/courses/-KgVwEBq5wbFnjj7O8Fp.json) .switchMap(course = course.description+= - TEST ; return this.http.put(/courses/-KgVwEBq5wbFnjj7O8Fp.json, course) , (firstHTTPResult, secondHTTPResult) = firstHTTPResult, secondHTTPResult); sequence$.subscribe(values = console.log(result observable , values) ); 请求异常处理throwError() this.http .get(/api/simulate-error) .catch( error = / here we can show an error message to the user, / for example via a service console.error(error catched, error); return Observable.of(description: Error Value Emitted); ) .subscribe( val = console.log(Value emitted successfully, val), error = console.error(This line is never called ,error); , () = console.log(HTTP Observable completed.) ); 当发生异常时,控制台的输出结果:Error catched HttpErrorResponse headers: HttpHeaders, status: 404, statusText: Not Found, url: http:/localhost:4200/api/simulate-error, ok: false, Value emitted successfully description: Error Value Emitted HTTP Observable completed.Http 拦截器定义拦截器import Injectable from angular/core; import HttpEvent, HttpHandler, HttpInterceptor from angular/common/http; import HttpRequest from angular/common/http; import Observable from rxjs/Observable; Injectable() export class AuthInterceptor implements HttpInterceptor constructor(private authService: AuthService) intercept(req: HttpRequest, next: HttpHandler): ObservableHttpEvent const clonedRequest = req.clone( headers: req.headers.set(X-CustomAuthHeader, authService.getToken() ); console.log(new headers, clonedRequest.headers.keys(); return next.handle(clonedRequest); 配置拦截器NgModule( declarations: AppComponent , imports: BrowserModule, HttpClientModule , providers: provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true , bootstrap: AppComponent ) export class AppModule Http 进度事件longRequest() const request = new HttpRequest( POST, /api/test-request, , reportProgress: true); this.http.request(request) .subscribe( event = if (event.type = HttpEventType.DownloadProgress) console.log(Download progress event, event); if (event.type = HttpEventType.UploadProgress) console.log(Upload progress event, event); if (event.type = HttpEventType.Response) console.log(response received., event.body); ); 上面示例运行后,控制台的可能的输出结果:Upload progress event Object type: 1, loaded: 2, total: 2 Download progress event Object type: 3, loaded: 31, total: 31 Response Received. Object description: POST Response第九节 - 注入服务基础知识组件中注入服务步骤(1) 配置已创建的服务,如:NgModule( / . providers: MemberService ) export class AppModule (2) 导入已创建的服务,如:import MemberService from ./member.service;(3) 使用构造注入方式,注入服务:export class MembersComponent implements OnInit / . constructor(private memberService: MemberService) 服务使用示例创建 MemberService 服务import Injectable from angular/core; import Http from angular/http; Injectable() export class MemberService constructor(private http: Http) getMembers() return this.http .get(/orgs/angular/members?page=1&per_page=5) .map(res = res.json() 配置 MemberService 服务import MemberService from ./member.service; NgModule( / . providers:MemberService, bootstrap: AppComponent ) export class AppModule 使用 MemberService 服务/ . import MemberService from ./member.service; Component(.) export class MembersComponent implements OnInit members: Member; constructor(private memberService: MemberService) ngOnInit() this.memberService.getMembers() .subscribe(data = if (data) this.members = data; ); 第十节 - 路由模块简介基础知识导入路由模块/ . import RouterModule from angular/router; NgModule( imports: BrowserModule, FormsModule, HttpModule, RouterModule, declarations: AppComponent, UserComponent, MembersComponent, bootstrap: AppComponent ) export class AppModule 配置路由信息import Routes, RouterModule from angular/router; import UserComponent from ./ponent; export const ROUTES: Routes = path: user, component: UserComponent ; NgModule( imports: BrowserModule, RouterModule.forRoot(ROUTES) , / . ) export class AppModule routerLink 指令为了让我们链接到已设置的路由,我们需要使用 routerLink
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 如何推动农业科技与产业融合发展
- 小区停车管理规定解析
- 化学品生产工艺技术规定
- 2025浙江金华市武义县司法局招聘4人笔试含答案
- 如何让绿植更好抵御寒冬
- 职业教育学习规范
- 心肌酶检测方法
- 2025西安国际港务区陆港第七小学招聘笔试含答案
- 2025年碳资产管理师考试题库(附答案和详细解析)
- 2025年事业单位工勤技能-广东-广东计算机信息处理员三级高级历年参考题库含答案解析
- 涂塑钢管焊接施工方案
- DB21-T 4079-2024 畜禽养殖场污水贮存设施建设规范
- 地产楼盘售卖合同范例
- 诚信培训教育课件
- 人教版八年级上册历史的知识点
- 马凡氏综合征课件
- 中国共产主义青年团团章
- 《信息技术基础》高职全套教学课件
- 《 人体解剖学 》课程标准-康复治疗技术等专业(2022年修改)
- 格构柱、杯形基础钢结构工程施工组织设计
- 2024公安机关人民警察高级执法资格考试题(解析版)
评论
0/150
提交评论