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. { path: '', redirectTo: '/dashboard', pathMatch: 'full' }

  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
您的支持是對博主最大的鼓勵,感謝您的認真閱讀。
本文版權歸作者所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM