Angular 快速学习笔记(1) -- 官方示例要点

  1. 创建组件 ng generate component heroes

  2. {{ hero.name }} {{}}语法绑定数据

  3. 管道pipe 格式化数据

    <h2>{{ hero.name | uppercase }} Details</h2>
    
  4. [(ngModel)] 双向绑定,form需要引入FormsModule

  5. AppModule 放置元数据(metadata)
    a. @NgModule 装饰器 imports导入外部模块
    b. declarations 放置组件

     @NgModule({
       declarations: [
         AppComponent,
         HeroesComponent
       ],
       imports: [
         BrowserModule,
         FormsModule
       ],
       providers: [],
       bootstrap: [AppComponent]
     })
    
  6. *ngFor Angular 的复写器(repeater)指令,使用let xx of xxs遍历

  7. 绑定click使用 (click)

     <li *ngFor="let hero of heroes" (click)="onSelect(hero)"> 
    
  8. *ngIf 条件判断

     <div *ngIf="selectedHero">
    
  9. 条件css类

     [class.selected]="hero === selectedHero"
    
  10. 组件的输入参数,需要使用 @Input() 装饰器

    @Component({
      selector: 'app-hero-detail',
      templateUrl: './hero-detail.component.html',
      styleUrls: ['./hero-detail.component.css']
    })
    

    a. @Input() hero: Hero
    b. <app-hero-detail [hero]="selectedHero">

  11. 服务
    a. 组件不应该直接获取或保存数据,它们不应该了解是否在展示假数据。 它们应该聚焦于展示数据,而把数据访问的职责委托给某个服务
    b. 服务负责业务数据获取和保存,让组件只需要关注展示
    c. 通过注入,服务可以在多个“互相不知道”的类之间共享信息
    d. 创建服务 ng generate service hero

    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root',
    })
    export class HeroService {
      constructor() { }
    }
    

    e. Injectable 可依赖注入装饰器

  12. 依赖注入的接入(提供 provide)
    a. 使用service之前,需要将服务提供给依赖注入系统,提供注册一个provider来实现
    b. Angular CLI 命令 ng generate service 会通过给 @Injectable 装饰器添加元数据的形式 providedIn: 'root', 当你在顶层提供该服务时,Angular 就会为 HeroService 创建一个单一的、共享的实例,并把它注入到任何想要它的类上
    c. 如何注入 Service,在component添加私有构造函数
    constructor(private heroService: HeroService) { }
    1. 声明了一个私有 heroService 属性,
    2. 把它标记为一个 HeroService 的注入点

  13. 在ngOnInit 中调用service获取数据
    a. 虽然构造函数也可以调用,但是我们需要让构造函数保持简单,只做初始化操作
    b. 使用ngOnInit 生命周期钩子中调用服务

  14. RXJS 处理异步操作
    a. 异步处理可以使用回调函数,可以返回 Promise(承诺),也可以返回 Observable(可观察对象)
    b. angular使用了Rxjs,因此使用Observable,Observable 是 RxJS 库中的一个关键类
    c. 引入import { Observable, of } from 'rxjs'

    getHeroes(): Observable<Hero[]> {
      return of(HEROES);
    }
    

of(HEROES) 会返回一个 Observable<Hero[]>,它会发出单个值,这个值就是这些模拟英雄的数组。
d. 订阅Observable

	 this.heroService.getHeroes()
	      .subscribe(heroes => this.heroes = heroes);
  1. 组件可绑定public的service的属性

    export class MessageService {
      messages: string[] = [];
    }
    constructor(public messageService: MessageService) {}
    <div *ngFor='let message of messageService.messages'> {{message}} </div>
    
  2. 路由
    a. Angular 的最佳实践之一就是在一个独立的顶级模块中加载和配置路由器,它专注于路由功能,然后由根模块 AppModule 导入它
    b. ng generate module app-routing --flat --module=app
    c. 添加路由 ,路由定义 会告诉路由器,当用户点击某个链接或者在浏览器地址栏中输入某个 URL 时,要显示哪个视图,因此路由包含两个属性:
    i. path:一个用于匹配浏览器地址栏中 URL 的字符串
    ii. component:当导航到此路由时,路由器应该创建哪个组件

    	const routes: Routes = [
    	  { path: 'heroes', component: HeroesComponent }
    	];
    
  3. 初始化路由
    a. 要使用路由,必须首先初始化路由器,并让它开始监听浏览器中的地址变化
    b. 把 RouterModule 添加到 @NgModule.imports 数组中,并用 routes 来配置它
    c. imports: [ RouterModule.forRoot(routes) ],

  4. 路由出口(RouterOutlet)

    	<h1>{{title}}</h1>
    	<router-outlet></router-outlet>
    	<app-messages></app-messages>
    
  5. 路由链接 (routerLink),在a里添加routerLink

    <a routerLink="/heroes">Heroes</a>
    
  6. 默认路由
    a.

  7. 参数化路由
    a. { path: 'detail/:id', component: HeroDetailComponent }
    b. 在component中,构造函数增加ActivatedRoute 、location
    i. ActivatedRoute 保存着到lComponent 实例的路由信息,this.route.snapshot.paramMap.get('id')
    ii. location 是一个 Angular 的服务,用来与浏览器打交道,this.location.back() 返回上一页

  8. HTTP
    a. HttpClient 是 Angular 通过 HTTP 与远程服务器通讯的机制
    b. 使用http,需要在AppModule中, @angular/common/http 中导入 HttpClientModule 符号,并把它加入 @NgModule.imports 数组
    c. 使用

    	getHeroes (): Observable<Hero[]> {
    	  return this.http.get<Hero[]>(this.heroesUrl)
    	}
    
    d. 错误处理 使用 .pipe() 方法来扩展 Observable 的结果,并给它一个 catchError() 操作符
    
    	import { catchError, map, tap } from 'rxjs/operators';
    	getHeroes (): Observable<Hero[]> {
    	  return this.http.get<Hero[]>(this.heroesUrl)
    		.pipe(
    		  catchError(this.handleError('getHeroes', []))
    		);
    	}
    

catchError() 操作符会拦截失败的 Observable。 它把错误对象传给错误处理器,错误处理器会处理这个错误

		private handleError<T> (operation = 'operation', result?: T) {
		  return (error: any): Observable<T> => {

			// TODO: send the error to remote logging infrastructure
			console.error(error); // log to console instead

			// TODO: better job of transforming error for user consumption
			this.log(`${operation} failed: ${error.message}`);

			// Let the app keep running by returning an empty result.
			return of(result as T);
		  };
		}

在控制台中汇报了这个错误之后,这个处理器会汇报一个用户友好的消息,并给应用返回一个安全值,让它继续工作,可以使用tap窥探(tap)Observable

		getHeroes (): Observable<Hero[]> {
		  return this.http.get<Hero[]>(this.heroesUrl)
			.pipe(
			  tap(heroes => this.log(`fetched heroes`)),
			  catchError(this.handleError('getHeroes', []))
			);
		}
  1. 模板绑定Observable

  2. $ 是一个命名惯例,用来表明 heroes$ 是一个 Observable,而不是数组。 *ngFor 不能直接使用 Observable。 不过,它后面还有一个管道字符(|),后面紧跟着一个 async,它表示 Angular 的 AsyncPipe。
    private searchTerms = new Subject<string>();
    
    // Push a search term into the observable stream.
    search(term: string): void {
      this.searchTerms.next(term);
    }
    
    this.heroes$ = this.searchTerms.pipe(
    	  // wait 300ms after each keystroke before considering the term
    	  debounceTime(300),
    
    	  // ignore new term if same as previous term
    	  distinctUntilChanged(),
    
    	  // switch to new search observable each time the term changes
    	  switchMap((term: string) => this.heroService.searchHeroes(term)),
    	);
    

延伸阅读:


作者:Jadepeng
出处:jqpeng的技术记事本--http://www.cnblogs.com/xiaoqi
您的支持是对博主最大的鼓励,感谢您的认真阅读。
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

posted @ 2018-05-21 10:20  JadePeng  阅读(4340)  评论(0编辑  收藏  举报