Angular 转换 API 资料格式 (Adapter)

今天的内容属於设计模式的一种。
当我们从後端接到资料後,有时後资料格式往往不是如我们所想,所以会再加工做个转换的动作。
所以就要使用 TypeScript 来做个转接器,转成我们所需的资料!

就拿前几天的文章 Angular 如何取得 API 资料 继续做介绍罗


转换资料格式

这是原 api 取得的资料格式

{
  "id": 1,
  "title": "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops",
  "price": 109.95,
  "description": "Your perfect pack for everyday use and walks in the forest...",
  "category": "men's clothing",
  "image": "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg",
  "rating": {
    "rate": 3.9,
    "count": 120
  }
}

想转换为这样的资料格式

{
  "ngTitle": "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops",
  "ngDescription": "Your perfect pack for everyday use and walks in the forest...",
  "ngCategory": "men's clothing",
  "ngImage": "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg"
}

建立一个 model.ts

model.ts

// 欲转成的资料格式
export class List {
  constructor(
    public ngTitle: string,
    public ngCategory: string,
    public ngImage: string,
    public ngDescription: string
  ) {}
}

// 注入到 root
@Injectable({
  providedIn: "root",
})
export class ListAdapter {
  adapt(item: any): List {
    return new List(item.title, item.category, item.image, item.description);
  }
}

api service.ts

import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { catchError, map, Observable } from "rxjs";
import { List, ListAdapter } from "./app.model";

@Injectable()
export class AppService {
  constructor(
    private httpClient: HttpClient,
    private listAdapter: ListAdapter
  ) {}

  fetchProd(): Observable<List[]> {
    const url = `https://fakestoreapi.com/products`;
    return this.httpClient.get<any>(url).pipe(
      map((list) => {
        // 接到资料後做转换
        return list.map((item) => this.listAdapter.adapt(item));
      }),
      catchError((err, caught) => {
        throw err;
      })
    );
  }
}

资料就会转成我们需要的格式了


後记

今天的文章比较偏向设计模式的应用,当专案越来越大时,程序码耦合度越低越好,避免牵一发而动全身,改了 A 坏了 B 而花更多时间找问题点


范例:https://stackblitz.com/edit/angular-ivy-zsnxup

参考资料:
Consuming APIs in Angular: The Model-Adapter Pattern
适配器模式


<<:  Day29. Rails MVC 的 Model - 与资料库联络的桥梁

>>:  13. 克服团队的摩擦力

Day 2 ( 入门 ) 简单烟火动画

简单烟火动画 教学原文参考:简单烟火动画 这篇文章会介绍如何使用「重复无限次」、「显示指示灯」和「暂...

【Day 5】机器学习基本功(三) --- Regression

如何找到一个函式(function)?(下) 步骤一:写出一个带有未知参数的函式 昨天举的例子 是一...

【在厨房想30天的演算法】Day 12 资料结构:杂凑表 Hash Table

Aloha!又是我少女人妻 Uerica!以前我爸开车在停红绿灯的时候,总会趁着红灯几秒的空挡跟我玩...

资安入门

资讯安全是透过安全管制措施来保护资讯资产免於受到危害,以达到机密性、完整性和可用性(即常听到的CI...

让团队把事情做好:厘清任务很重要

成功打造好一个让团队感觉安全、平静的环境,是否就以足够?当然不是。接下来,我们来谈谈人的管理 — 如...