如何将JSON:API沿着与Angular/RxJs一起使用?

6bc51xsx  于 8个月前  发布在  Angular
关注(0)|答案(1)|浏览(90)

我有一个(Laravel)API,它遵循json:api spec。一切都工作得很好,使用Postman我可以请求相关的资源等。
我使用Angular作为我的前端,但我很难理解如何使用这个API。
我一直在阅读通过this SO thread作为一个起点。
我正在使用ngrx进行状态管理;我能够成功地发出从我的API获取数据所需的适当请求。
以下是我请求获取组织的响应示例:

// response from /api/v1/organization/:id

data: {...}
jsonapi: {...}
links: {...}

字符串
下面是我的Organization接口:

export interface IOrganization {
    data: object;
    jsonapi: object;
    links: object;

    // before json:api I would just use the below attributes
    id?: string;
    name: string;
    streetAddress1: string;
    createdAt?: Date;
    updatedAt?: Date;
    deletedAt?: Date;
}


在使用json:API之前,这个类是非常直接的。但是由于所有的数据现在都在data.attributes内部,我不知道如何正确地构造这个接口。
下面是我的organization.effects文件的一个很好的部分:

return this._organizationService
    .getOrganization(action.organizationId)
    .pipe(
        tap((organization) => {
            console.log(organization);   // {data:{...}, jsonapi: {...}, data:{...}
        }),
        map((organization) =>
            OrganizationApiActions.loadOrganizationSuccess({
                organization,
            })
   ),
   catchError((error) => {...}
    ...


解决方案是在这里向下钻取属性吗?

organization.data.id;
organization.data.attributes.name;


或者有没有更合理的方法来使用这个API?我看过ngx-jsonapi包,不知道这是不是太夸张了?
在过去使用vue.js时,我只使用jsona npm package
使用json:API(rest API)的理想方式是什么?

kiz8lqtg

kiz8lqtg1#

如果您不直接使用API(后端用于前端),

  • 有2个接口模型,
  • 一个描述后端响应(理想情况下是codegen或推断,而不是手动编写)
  • 以及要Map到的前端模型
  • 使用一个函数将后端对象Map到前端
  • 用于接收响应。
const mapJsonApiToOrganization = () =>
  map((response: OrganizationResponse) => {
    const { id, attributes } = response.data;
    return {
      id,
      name: attributes.name,
      streetAddress1: attributes.streetAddress1,
      // ... other mappings
    };
  });

// In your effect
return this._organizationService.getOrganization(action.organizationId).pipe(
  mapJsonApiToOrganization(),
  // from here frontend model only
  map((organization: Organization) => OrganizationApiActions.loadOrganizationSuccess({ organization })),
);

字符串
在我看来,我只会把数据传递给ngrx前端模型。如果你改变你的后端,你只想改变Map函数。
使用第三方软件包是一个判断电话。如果只是这5个属性的前端模型钻孔似乎罚款。

相关问题