angular - 处理将 API 对象映射到 UI 模型对象的模式

标签 angular typescript rxjs angular-http

我正在切换以使用新的 HttpClient Angular 。

正在调用的 API 以一种格式返回 json 数据。我想获取这些数据并将其转换为适合 UI 使用的 typescript 模型类。

我之前这样做的方法是使用 map 功能,例如

        return this.httpClient.get(url, { headers: headers })
        .map(mapFunction)
        .catch(errorFunction);

map 函数执行转换 api 响应的繁重工作,引入模型对象,例如
 const mapFunction =
            (response: Response) => {
                const data = response.json();
                const contacts: Contact[] = [];
                let i = 0;
                for (const result of data.resourceResults) {
                    i = i + 1;
                    const contact: Contact = new Contact();
                    contact.role = result.r

对我来说,这似乎很麻烦,我基本上是在寻找一种方法来将对象从 api 响应类型映射到 ui 模型类型,而不必为每个请求使用自定义映射函数。

最佳答案

如果没有明确指定需要映射的内容,就无法进行自定义映射。要么你告诉服务器端返回一个 UI 友好的响应,要么你需要在客户端自己做映射。

如果你想在客户端映射响应,你可以利用 Typescript 类,并使用它的 constructor快速生成你想要的项目:

export class Contact {
    public name:string;
    public roles:any;
    constructor(name:string, roles: any) {
        //specify your own constructor logic
        this.name=name;
        this.roles=roles
    }
}

现在你可以写在你的 mapFunction将响应显式转换为 Contact 的列表s。此外,您可以使用数组的 .map()遍历对象,而无需编写 for 循环:
public mapFunction = (response: Response) => {
    const data = response.json();
    const resource = data.resourceResults;
    //map it
    return resource.map(result => new Contact(result.n, result.r))
}

繁琐与否,我认为是主观的。但绝对可以以更优雅的方式编写代码。

关于angular - 处理将 API 对象映射到 UI 模型对象的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47632430/

相关文章:

具有可观察的 Angular 形式

typescript - TS : Index signature for type 'string' is missing in type 'IParam'

rx-java - 防止多次 api 调用

Marble 测试中的 Angular NgRx 效果错误 : Expected $. 长度 = 0 等于 2。/预期 $[0] = 未定义等于对象

json - 如何使用 angular4 将 appsettings.json 中的键值读取到 typescript 文件

typescript - 可观察变量的 Angular2 Observable.forkJoin - ReferenceError : Observable is not defined

javascript - ionic 2 : Object 'Date' doesn't work on Ios

typescript - 使用 Vue 构建 TypeScript 代码时 Webpack 构建错误

javascript - RxJS 管道过滤到 2+ 个分支

angular - 如何使用 Keycloak 获取当前用户名?