角度での一般的なCRUDサービス:第4部


カバー写真Xan Griffin on Unsplash .
この記事は、一般的なCRUDサービスとモデルを角度で作成する方法に関するシリーズの一部です.



  • 👉 第4部-角度での一般的なCRUDサービス

  • 汎用CRUDサービス
    コードの生成と書き込みを開始する前に、一歩後ろに戻り、より大きな写真を見ましょう.ジェネリックサービスは以下の引数を受け入れるべきです:
  • the HttpClient はHTTPリクエストに使用される
  • インスタンスを作成するためのモデルのクラス
  • APIエンドポイントのパス.
  • また、すべてのリソースには、CRUDに関連する5つの主要メソッドが必要です.

  • create -新しいリソースを返します.

  • get all -リストとしてすべてのリソースを取得します.

  • get by id - IDによって特定のリソースを返します.

  • update - idによって特定のリソースを更新します.

  • delete - idによって特定のリソースを削除します.
  • 偉大な、今一歩一歩を作成しましょう.

    1️⃣ クリエイト
    The create() メソッドは、引数として部分モデルを受け入れ、作成したモデルをサーバーから返します.リソースを作成する前に、一部のプロパティは利用できません.id , createdAt , など).また、結果をモデルのクラスのインスタンスに変換します.

    TIP: All methods try to create instances of model's class in order to apply and benefit extra functionality from them (e.g. convert string dates to actual Date in constructor or for future usage of their methods such as toJson() function).


    public create(resource: Partial<T> & { toJson: () => T }): Observable<T> {
      return this.httpClient
        .post<T>(`${this.apiUrl}`, resource.toJson())
        .pipe(map((result) => new this.tConstructor(result)));
    }
    

    2️⃣ すべてゲット
    The get() メソッドはObservable 既存のすべてのリソースの一覧を表示します.これは引数を受け入れず、リストを繰り返して単純なJSONオブジェクトの代わりに複数のインスタンスを作成します.
    public get(): Observable<T[]> {
      return this.httpClient
        .get<T[]>(`${this.apiUrl}`)
        .pipe(map((result) => result.map((i) => new this.tConstructor(i))));
    }
    

    3️⃣ IDで取得する
    次の読み込み方法はgetById() . 明らかに、引数としてtypenumber を返し、Observable 既存のリソースインスタンスの.
    public getById(id: number): Observable<T> {
      return this.httpClient
        .get<T>(`${this.apiUrl}/${id}`)
        .pipe(map((result) => new this.tConstructor(result)));
    }
    

    4️⃣ 更新
    既存のリソースを更新する場合、update() メソッド.部分モデル(例えば更新するプロパティのみ)を受け入れ、更新されたインスタンスをObservable .
    public update(resource: Partial<T> & { toJson: () => T }): Observable<T> {
      return this.httpClient
        .put<T>(`${this.apiUrl}/${resource.id}`, resource.toJson())
        .pipe(map((result) => new this.tConstructor(result)));
    }
    

    5️⃣ 削除
    最後にdelete() メソッドは、指定したIDによってサーバから既存のリソースを完全に削除します.モデルのIDにマッチする引数として数値を受け取りますが、何も返さないObservable<void> ).
    public delete(id: number): Observable<void> {
      return this.httpClient.delete<void>(`${this.apiUrl}/${id}`);
    }
    

    ➡️ 最終結果
    一度にすべてのメソッドを説明したら、今ではジェネリックサービスの最終結果を見るまでの時間です.
    import { HttpClient } from '@angular/common/http';
    import { Observable } from 'rxjs';
    import { map } from 'rxjs/operators';
    
    import { ResourceModel } from 'your-path-to-model'; // see: Part 3
    
    export abstract class ResourceService<T extends ResourceModel<T>> {
      constructor(
        private httpClient: HttpClient,
        private tConstructor: { new (m: Partial<T>, ...args: unknown[]): T },
        protected apiUrl: string
      ) {}
    
      public create(resource: Partial<T> & { toJson: () => T }): Observable<T> {
        return this.httpClient
          .post<T>(`${this.apiUrl}`, resource.toJson())
          .pipe(map((result) => new this.tConstructor(result)));
      }
    
      public get(): Observable<T[]> {
        return this.httpClient
          .get<T[]>(`${this.apiUrl}`)
          .pipe(map((result) => result.map((i) => new this.tConstructor(i))));
      }
    
      public getById(id: number): Observable<T> {
        return this.httpClient
          .get<T>(`${this.apiUrl}/${id}`)
          .pipe(map((result) => new this.tConstructor(result)));
      }
    
      public update(resource: Partial<T> & { toJson: () => T }): Observable<T> {
        return this.httpClient
          .put<T>(`${this.apiUrl}/${resource.id}`, resource.toJson())
          .pipe(map((result) => new this.tConstructor(result)));
      }
    
      public delete(id: number): Observable<void> {
        return this.httpClient.delete<void>(`${this.apiUrl}/${id}`);
      }
    }
    
    最後に、ここではユーザのサービスの例を示します.
    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    import { User } from 'your-path-to-user-model';
    import { ResourceService } from 'your-path-to-resource-service';
    
    @Injectable({ providedIn: 'root' })
    export class UsersService extends ResourceService<User> {
      constructor(private http: HttpClient) {
        super(http, User, `your-api-of-users-here`);
      }
    }
    
    StackBlitzで最終的なソースコードを見つけることができます.

    結論✅
    ああ!我々は最後までそれを作った!🙌
    私はあなたが記事のこのシリーズを楽しんで、あなたのアプリケーションのコードをさらに一般的かつ再利用可能な乾燥原理に従うようになります願っています.また、CRUD機能だけでなく、それがジェネリックを使用することによってあなたのアプリで可能であるときはいつでも、この記事を使うことを望みます.
    この記事(前の部分)をあなたの❤️ 🦄 🔖 それがより広い聴衆に広がるのを援助するために.🙏
    また、ここにあなたのコメントやTwitterのDMSを残して質問がある場合は、私に連絡することを躊躇しないでください.
    ニックス・アニフ✍️