1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Angular勉強会 #9 パイプ、DI導入

Last updated at Posted at 2021-05-19
1 / 11

Pipeとは

  • Template構文の中で用いる、データ変換を行う仕組み
  • Linux の パイプ処理 に概念的には近い
    • ps | grep node みたいなやつ

Pipeの利用例

<div>{{ 'HELLO' | translate }}</div>

組み込みのPipe

  • AsyncPipe
  • CurrencyPipe
  • UpperCasePipe/LowerCasePipe

他、以下のようなものがある。
https://angular.io/api/common#pipes


自作のPipe

@Pipe デコレータを利用したクラスを作成することで実現する。また、Componentと同様にapp.module.tsdeclerarions に追加が必要

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
  transform(value: number, exponent?: number): number {
    return Math.pow(value, isNaN(exponent) ? 1 : exponent);
  }
}

これまでのおさらい / Angularのポイント

  • 依存関係や定義を明確に定義することで、パーツごとの管理をやりやすくする module 機構
  • UIをページごと、部品ごとに分割し、再利用しやすくする component 機構
  • UIとコードとのデータのやり取りを実現する binding 機構
  • 異なるUI部品に対して共通的な処理を追加できる directive 機構
  • 文字列や数値などのデータの変換処理を簡便に記述できる pipe 機構

最後は設計の話 / 依存性注入(Dependency Injection)について


DIとは何か(再掲)

DIとはもともとはJavaなどのサーバーサイドの分野でよく用いられてきた、疎結合を保ったまま依存関係を構築する手法である。

DIを実現する仕組みをDIコンテナといい、Angularにもその仕組は組み込まれている。主な挙動としては以下のようになる。

  1. サービスを利用するクラス側が、どのサービスが必要かを記述する。
  2. DIコンテナにサービスを登録する
  3. DIコンテナが起動時に依存性を解決し、生成したサービスをクラスに注入する

image.png


なんでそんなややこしいことするんですか?

image.png


DIのポイント

  • 実クラスではなく、抽象クラス/インタフェースを参照することで、クラス間を疎結合に保つ
    • 変更の影響範囲の限定
    • テスタビリティの向上(モックの導入)
  • 依存性を逆転させることで、モジュールの可搬性を上げる

image.png


そして、Clean Architectureへ

image.png

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?