【问题标题】:EmberJS getting user profile informationEmberJS 获取用户配置文件信息
【发布时间】:2017-04-19 15:57:36
【问题描述】:

在我的 Rails API 中,我使用的是 Ember 默认期望的 JSONAPI 结构。

我有一个 Rails 路由 http://localhost:3000/profile,它将返回当前登录的用户 JSON。

如何在 Emberjs 中向 /profile 端点发出任意请求,以便在路由器的 model() 挂钩中获取登录用户的 JSON?

我尝试在此处遵循本指南:

https://guides.emberjs.com/v2.10.0/models/finding-records/

并且有这个代码:

return this.get('store').query('user', {
  filter: {
    email: 'jim@gmail.com'
  }
}).then(function(users) {
  return users.get("firstObject");
});

但是它返回了不正确的用户。似乎“电子邮件”的值是什么并不重要,我可以将它传递给“泥”,它会返回我数据库中的所有用户。

我是否无法在 Ember 中我的个人资料路由的 model() 挂钩中向 /profile 发出简单的 GET 请求?

更新

我注意到 Ember 中的过滤器实际上只是在请求 URL 的末尾附加了一个查询参数。

所以有了我上面的过滤器,就像发出请求一样:

GET http://localhost:3000/users?filter['email']=jim@gmail.com

这无济于事,因为我的 Rails 对过滤器查询参数一无所知。

我希望 Ember 会自动找到用户并执行一些黑魔法来过滤用户以匹配我的电子邮件地址,而不是我必须在我的 Rails API 中手动构建额外的逻辑来查找单个记录。

Hurrmmmmmmm...确实感觉我现在正在与 Ember 的惯例作斗争。

更新

感谢 Lux,我终于用以下方法让它工作了:

第 1 步 - 生成用户适配器:

ember generate adapter user

第 2 步 - 在用户适配器的 queryRecord 方法覆盖中编写 AJAX 请求

import ApplicationAdapter from './application';
import Ember from 'ember';

export default ApplicationAdapter.extend({
  apiManager: Ember.inject.service(),

  queryRecord: function(store, type, query) {
    if(query.profile) {
      return Ember.RSVP.resolve(
        Ember.$.ajax({
          type: "GET",
          url: this.get('apiManager').requestURL('profile'),
          dataType: 'json',
          headers: {"Authorization": "Bearer " + localStorage.jwt}
        })
      );
    }
  }
});

第 3 步 - 像这样发出 model() 挂钩请求:

import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return this.get('store').queryRecord('user', {profile: true});
  }
});

【问题讨论】:

    标签: ruby-on-rails ember.js ember-data ember-cli


    【解决方案1】:

    好吧,query 用于服务器端过滤。如果您希望它在客户端使用类似store.findAll('user').then(users => users.findBy('email', 'bla@bla.bla'));

    但这不是你想要的。你有你的服务器端过滤器。它就在/profile 之下。不在/user下。

    无论/profile 实际响应的内容多么有趣。单记录响应或多记录响应。最好的可能是单一记录响应,因为您只想返回一个用户。那么我们如何用 ember 做到这一点呢?好吧,我们使用store.queryRecord()

    因为 ember 不知道任何关于 /profile 的信息,我们必须在 user-adapter 中使用类似这样的内容告诉它:

    queryRecord: function(store, type, query) {
      if(query.profile) {
        return Ember.RSVP.resolve(Ember.$.getJSON('/profile'));
      }
    }
    

    然后你可以直接返回store.queryRecord('user', { profile: true })

    【讨论】:

    • 如何使用 queryRecord 方法?我试过return this.get('store').queryRecord('profile', {});,但我收到错误Error while processing route: profile No model was found for 'profile' Error: No model was found for 'profile'
    • 我想我明白了(请参阅我用新代码更新的问题)。我希望我能给你加倍的投票:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    相关资源
    最近更新 更多