最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Angular實踐之將Input與Lifecycle轉(zhuǎn)換成流示例詳解

 更新時間:2023年02月17日 14:45:00   作者:Lian?Shenghua  
這篇文章主要為大家介紹了Angular實踐之將Input與Lifecycle轉(zhuǎn)換成流示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

將 Input 和生命周期函數(shù)轉(zhuǎn)換成流

在 Angular 中一直有一個期待,就是希望能夠?qū)?Input 和生命周期函數(shù)轉(zhuǎn)換成流,實際上我們可以通過比較簡單的方式實現(xiàn),比如說:

class NameComponent {
  @Input() name: string;
}

我們要實現(xiàn)一個 input 為 name, output 為 hello name 的簡單 component。如果將 input 看成是一個流的話,就會比較容易實現(xiàn)。常見的流轉(zhuǎn)換方式是通過 set 方法實現(xiàn):

class NameComponent {
  private name$ = new Subject(1);
  private _name: string;
  @Input() set name(val: string) {
    this.name$.next(val);
    this._name = val;
  }
  get name() {
    return this._name;
  }
  @Output() helloName = this.name$.pipe(
    map(name => `hello ${name}`),
  );
}

這樣寫是可以,不過你也看出來了,有一個問題,就是麻煩。

對于生命周期函數(shù),我們也有類似的需求。比如說,我們經(jīng)常需要在 Angular 銷毀的時候,unsubscribe 所有的 subscription。

class NameComponent implements OnDestroy {
  private destory$ = new Subject<void>();
  ngOnDestroy(): void {
    destory$.next();
    destory$.complete();
  }
}

如果需要使用其他的生命周期函數(shù)的話,每個函數(shù)都需要這樣手動調(diào)用一次。

思路

如果回到 input 的問題的話,我們知道,獲取 input 的變化,除了 set 方法,還有 ngOnChanges 函數(shù)。我們很容易想到一個思路:

  • 將 ngOnChanges 轉(zhuǎn)換成一個 stream, onChanges$
  • 通過 onChanges$ map 成 input stream
private onChanges$ = new Subject<SimpleChanges>();
@Input() name: string;
name$ = this.onChanges$.pipe(
  switchMap(simpleChanges => {
    if ('name' in simpleChanges) {
      return of(simpleChanges?.name?.currentValue);
    }
    return EMPTY;
  }),
)
ngOnChanges(simpleChanges: SimpleChanges) {
  this.onChanges$.next(simpleChanges);
}

當然,ngOnChanges 只會在 input 變化的時候觸發(fā),所以我們還需要加上 init 以后的初始值。(當然,我們也要將 afterViewInit 轉(zhuǎn)換成 stream)

name$ = afterViewInit$.pipe(
  take(1),
  map(() => this.name),
  switchMap(value => this.onChanges$.pipe(
    startWith(value),
    if ('name' in simpleChanges) {
      return of(simpleChanges?.name?.currentValue);
    }
    return EMPTY;
  )),
) 

抽離成一個方法

很明顯,如果 input 比較多的話,這樣寫就比較冗余了。很容易想到我們可以把它抽離成一個方法。

export function getMappedPropsChangesWithLifeCycle<T, P extends (keyof T & string)>(
  target: T,
  propName: P,
  onChanges$: Observable<SimpleChanges>,
  afterViewInit$: Observable<void>) {
  if (!onChanges$) {
    return EMPTY;
  }
  if (!afterViewInit$) {
    return EMPTY;
  }
  return afterViewInit$.pipe(
    take(1),
    map(() => target?.[propName]),
    switchMap(value => target.onChanges$.pipe(
      startWith(value),
      if (propName in simpleChanges) {
        return of(simpleChanges?.[propName]?.currentValue);
      }
      return EMPTY;
    ))
  ) 
}

看到這里,你可能很容易就想到了,我們可以把這個方法變成一個 decorator,這樣看起來就簡潔多了。比如我們定義一個叫做 InputMapper 的裝飾器:

export function InputMapper(inputName: string) {
  return function (target: object, propertyKey: string) {
    const instancePropertyKey = Symbol(propertyKey);
    Object.defineProperty(target, propertyKey, {
      get: function () {
        if (!this[instancePropertyKey]) {
          this[instancePropertyKey] = getMappedPropsChangesWithLifeCycle(this, inputName, this['onChanges$']!, this['afterViewInit$']!);
        }
        return this[instancePropertyKey];
      }
    });
  };
}

值得注意的是,因為 target 會是 component instance 的 proto,會被所有的 instance 共享,所以我們在定義變量的時候,可以通過 defineProperty 中的 get 函數(shù)將變量定義到 this 上。這樣 component instance 在調(diào)用的時候就可以成功將內(nèi)容 apply 到 instance 而費 component class 的 prototype 上。

當然,使用的時候就會方便很多了:

class NameComponent {
  private onChanges$ = new Subject<SimpleChanges>();
  private afterViewInit$ = new Subject<void>();
  @Input() name: string;
  @InputMapper('name') name$!: Observable<string>;
  ngOnChanges() {
  ...
  } 
  ngAfterViewInit() {
  ...
  }
}

當然,因為對于生命周期函數(shù),也是重復(fù)性工作,我們很容易想到,是否能夠也能通過裝飾器實現(xiàn)。

重寫生命周期函數(shù)

我們只需要重寫生命周期函數(shù)就可以巧妙的實現(xiàn)了:

export function LifeCycleStream(lifeCycleMethodName: LifeCycleMethodName) {
  return (target: object, propertyKey: string) => {
    const originalLifeCycleMethod = target.constructor.prototype[lifeCycleMethodName];
    const instanceSubjectKey = Symbol(propertyKey);
    Object.defineProperty(target, propertyKey, {
      get: function () {
        if (!this[instanceSubjectKey]) {
          this[instanceSubjectKey] = new ReplaySubject(1);
        }
        return this[instanceSubjectKey].asObservable();
      }
    });
    target.constructor.prototype[lifeCycleMethodName] = function () {
      if (this[instanceSubjectKey]) {
        this[instanceSubjectKey].next.call(this[instanceSubjectKey], arguments[0]);
      }
      if (originalLifeCycleMethod && typeof originalLifeCycleMethod === 'function') {
        originalLifeCycleMethod.apply(this, arguments);
      }
    };
  }
}

那么我們可以將之前工作簡化為:

class NameComponent {
  @LifeCycleStream('ngOnChanges') onChanges$: Observable<SimpleChanges>;
  @LifeCycleStream('ngAfterViewInit') ngAfterViewInit$: Observable<void>;
  @Input() name: string;
  @InputMapper('name') name$!: Observable<string>;
  ...
  ...
}

然后,因為我們已經(jīng)實現(xiàn)了 InputMapper,那么很容易想到,有沒有可能把 onChanges$afterViewInit$ 放進 InputMapper,這樣我們就可以減少重復(fù)的調(diào)用了。我們可以把 LifeCycleStream 中的主體邏輯抽離成一個方法:applyLifeCycleObservable,然后在 InputMapper 調(diào)用就可以了:

if (!('afterViewInit$' in target)) {
  applyLifeCycleObservable('ngAfterViewInit', target, 'afterViewInit$');
}
if (!('onChanges$' in target)) {
  applyLifeCycleObservable('ngOnChanges', target, 'onChanges$');
}

當然,我們在調(diào)用前需要檢查這個 stream 是否已經(jīng)存在。注意,這里不要直接調(diào)用 target['ngAfterViewInit'], 因為我們之前寫了 get 函數(shù)??梢运伎枷聻槭裁?。(防止將 ngAfterViewInit apply 到 target 上去)

最后,我們來看一下最終的代碼:

class NameComponent {
  @Input() name: string;
  @InputMapper('name') name$!: Observable<string>;
}

這樣,既沒有破壞已有的 angular input,又能夠很快的實現(xiàn),input to stream 的轉(zhuǎn)換,還是比較方便的。

以上就是Angular實踐之將Input與Lifecycle轉(zhuǎn)換成流示例詳解的詳細內(nèi)容,更多關(guān)于Angular將Input Lifecycle轉(zhuǎn)流的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

周口市| 江孜县| 天水市| 伽师县| 阜平县| 始兴县| 虞城县| 社会| 名山县| 美姑县| 偏关县| 六枝特区| 瓦房店市| 双桥区| 郎溪县| 侯马市| 定远县| 偃师市| 永靖县| 台东县| 曲周县| 芮城县| 吴忠市| 新和县| 静宁县| 荆门市| 禹城市| 资兴市| 孝义市| 五华县| 漠河县| 贵南县| 黎平县| 平顶山市| 庄浪县| 涡阳县| 积石山| 麻江县| 南平市| 于田县| 太白县|