Emberjs-如何将api json响应Map到模型?

r1zk6ea1  于 2022-10-20  发布在  其他
关注(0)|答案(1)|浏览(170)

尝试构建Ember时。js示例应用程序调用REST Api并显示结果。我能够调用、获取并显示结果。在组件中,我正在阅读json响应结果。
如何将response dataMap到预定义模型,并在组件中使用它?我在https://guides.emberjs.com/release/models/defining-models/或https://guides.emberjs.com/release/in-depth-topics/making-api-requests/#toc_where-发出api请求
代码详细信息:
1.使用此示例API https://reqres.in/api/users
1.型号:(--更新--)

export default class UserModel extends Model {
  @attr('string') id;
  @attr('string') firstname;
  @attr('string') lastname;
  @attr('string') email;
  @attr('string') avatar;
}

1.路线:

export default class UsersRoute extends Route {
  async model() {
    let response = await fetch('https://reqres.in/api/users');
    let data = await response.json();
    return data.data;
  }
}

1.模板:

<UserList
  @title="List of Users"
  @users={{@model}}
/>

1.组件:

{{#each @users as |user|}}
    <tr>
      <td>{{user.id}}</td>
       <td>{{user.first_name}}</td>
       <td>{{user.last_name}}</td>
       <td>{{user.email}}</td>
    </tr>
  {{/each}}
mu0hgdu0

mu0hgdu01#

生成用户模型:
ember g model user

import Model, { attr } from '@ember-data/model';

export default class UserModel extends Model {
  @attr('string') email;
  @attr('string') firstName;
  @attr('string') lastName;
  @attr('string') avatar;
}

生成应用程序适配器和序列化程序:

ember g adapter application
ember g serializer application

将API URL添加到适配器:

import JSONAPIAdapter from '@ember-data/adapter/json-api';

export default class ApplicationAdapter extends JSONAPIAdapter {
  host = 'https://reqres.in/api'; // the `users` part of the path is autogenerated based on the model name
}

更新序列化程序:

import JSONSerializer from '@ember-data/serializer/json'; // note that this is not the default serializer, JSONAPISerializer
import { underscore } from '@ember/string';

export default class ApplicationSerializer extends JSONSerializer {
  // specify underscore-formatted keys
  keyForAttribute(attr) {
    return underscore(attr);
  }

  // use the `data` property in the payload as the serializable response
  normalizeResponse(store, primaryModelClass, payload, id, requestType) {
    payload = payload.data;
    return super.normalizeResponse(store, primaryModelClass, payload, id, requestType);
  }
}

更新路由以使用Ember Data方法而不是原始fetch

import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class UsersRoute extends Route {
  @service store;

  model() {
    return this.store.findAll('user');
  }
}

最后,您可以使用数据(使用camelcase格式的属性):

{{#each @users as |user|}}
  <tr>
    <td>{{user.id}}</td>
    <td>{{user.firstName}}</td>
    <td>{{user.lastName}}</td>
    <td>{{user.email}}</td>
  </tr>
{{/each}}

相关问题