angular11源碼探索五[管道源碼篇]

ngNonBindable

原樣輸出html

<span ngNonBindable>{{text}}</span>

Location

Angular Location 服務用於與瀏覽器URL進行交互,使用他來讀取當前URL,修改或者前進或者後退json

Angular Router 導航到應用程序的不一樣的位置,Location不執行導航,但容許咱們操做URL,他徹底繞過了Angular Router數組

一般咱們用它來返回上一個歷史記錄promise

location.back()

或者獲取當前路徑瀏覽器

this.location.path()

最好使用路由器服務來觸發路由更改。僅在須要操縱路由器而不會致使頁面刷新時才使用定位服務。async

asyncPipe

<h1>{{num|async}}</h1>
<h1>{{promise1|async}}</h1>

  num: Observable<number>= interval(1000)
  promise1=Promise.resolve('成功')

不須要寫取消訂閱,源碼中實現了函數

ngOnDestroy(): void {
    if (this._subscription) {
      this._dispose();
    }
  }

 private _dispose(): void {
    this._strategy.dispose(this._subscription!);
    this._latestValue = null;
    this._subscription = null;
    this._obj = null;
  }
   dispose(subscription: Unsubscribable): void {
    subscription.unsubscribe();
  }

  onDestroy(subscription: Unsubscribable): void {
    subscription.unsubscribe();
  }

lowercase

直接上源碼jsonp

@Pipe({name: 'lowercase'})
export class LowerCasePipe implements PipeTransform {
  /**
   * @param value The string to transform to lower case.
   */
  transform(value: string): string;
  transform(value: null|undefined): null;
  transform(value: string|null|undefined): string|null;
  transform(value: string|null|undefined): string|null {
    if (value == null) return null;
    if (typeof value !== 'string') {
      throw invalidPipeArgumentError(LowerCasePipe, value);
    }
    return value.toLowerCase();
  }
}

比較簡單,這個就很少介紹了,輸入undefined/null 都返回的nullthis

titlecase

return value.replace(
        unicodeWordMatch, (txt => txt[0].toUpperCase() + txt.substr(1).toLowerCase()));
  }

uppercase

transform(value: string|null|undefined): string|null {
    if (value == null) return null;
    if (typeof value !== 'string') {
      throw invalidPipeArgumentError(UpperCasePipe, value);
    }
    return value.toUpperCase();
  }

datePipe

<h1>{{str|date:'yyyy-MM-dd h:mm:ss SSS'}}</h1>

JsonPipe

@Pipe({name: 'json', pure: false})
export class JsonPipe implements PipeTransform {
  /**
   * @param value A value of any type to convert into a JSON-format string.
   */
  transform(value: any): string {
    return JSON.stringify(value, null, 2);
  }
}

keyvaluePipe

arr = new Map([[1, 2], [3, 4]]);
  obj = {};
  obj1 = {a: 1, b: 2};
  map = new Map();
  map1 = new Map([[1, 2]])

<h1>{{arr|keyvalue|json}}</h1>
// [ { "key": 1, "value": 2 }, { "key": 3, "value": 4 } ]
<h1>{{obj|keyvalue|json}}</h1>
// []
<h1>{{obj1|keyvalue|json}}</h1>
// [ { "key": "a", "value": 1 }, { "key": "b", "value": 2 } ]
<h1>{{map|keyvalue|json}}</h1>
// []
<h1>{{map1|keyvalue|json}}</h1>
// [ { "key": 1, "value": 2 } ]
<div *ngFor="let item of (obj1|keyvalue)">
  {{item.key}}
</div>
// a
// b

<div>{{arr|keyvalue:arrFn}}</div>

  arrFn(a, b) {
    console.log(a, b);
    return a-b;
  }

源碼探索spa

compareFn: (a: KeyValue<K, V>, b: KeyValue<K, V>) => number = defaultComparator):
      Array<KeyValue<K, V>>|null {
    if (!input || (!(input instanceof Map) && typeof input !== 'object')) {
      return null;
    }
支持的類型主要是 object   Map
第二個參數 compareFn 用於排序
執行的是 defaultComparator
用於的 KeyValueDiffers 來檢測key,value的差別性

  if (differChanges) {
      this.keyValues = [];
      differChanges.forEachItem((r: KeyValueChangeRecord<K, V>) => {
        this.keyValues.push(makeKeyValuePair(r.key, r.currentValue!));
      });
      this.keyValues.sort(compareFn);
    }
   默認的狀況是對key進行升序排序,能夠查看 defaultComparator 函數

DecimalPipe number管道

{{1241144|number}}
// 默認千分  1,241,144
<h1>{{123|number:'.2'}}</h1>
// 保留兩位小數
'1.2-2'
* 小數點前至少顯示1位位數,默認設置爲1
* 小數點後至少顯示2位位數
* 小數點後顯示的最大整數位數

百分比
 let num=new PercentPipe('en-US')
    console.log(num.transform(1.23)); // 123%

num.transform(12.34323256,'0.0-2') //保留兩位小數

slicePipe

slicePipe:SlicePipe;
  ngOnInit(): void {
    this.slicePipe=new SlicePipe();
    console.log(this.slicePipe.transform([1, 2, 3, 4], 2));
  }
// [3,4]
  console.log(this.slicePipe.transform('abcdef', 2));
// cdef
  console.log(this.slicePipe.transform('abcdef', -3));
// def

<h1>{{[1,2,3,4]|slice:1:3}}</h1>
2,3

源碼部分

if (value == null) return null;
	// 報錯, 若是不是Array或者string
    if (!this.supports(value)) {
      throw invalidPipeArgumentError(SlicePipe, value);
    }

    return value.slice(start, end);
  }

  private supports(obj: any): boolean {
    return typeof obj === 'string' || Array.isArray(obj);
  }


函數頭
{{[1,2,3,4]|slice:1:3}}
對應的參數是 value 數組   strat 1    end 3
transform(value: string|null|undefined, start: number, end?: number)
相關文章
相關標籤/搜索