本文介绍了使Loopback API Ember.js兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一个与Ember对话的API的Loopback。

I'm trying out Loopback for an API that will talk to Ember.

Ember需要将JSON包含在keys中,例如对于一个帐户:

Ember requires JSON to be contained in 'keys', e.g. for an account:

{ account:
   { domain: 'domain.com',
     subdomain: 'test',
     title: 'test.domain.com',
     id: 1 
} }

我在Google小组上发现了一些有关如何更改响应的建议,以便Ember将使用afterRemote钩子接收它。

I've found some advice on the Google group about how to alter the response so that Ember will receive it, using afterRemote hooks.

例如。在我的模型/ account.js中:

E.g. in my models/account.js:

module.exports = function(Account) {

    Account.afterRemote('**', function (ctx, account, next) {
      if(ctx.result) {
        if(Array.isArray(ctx.result)) {
          ctx.res.body = { 'accounts': account };
        } else {
          ctx.res.body = { 'account': account };
        }
      }

      console.log(ctx.res.body);

      next();
    });

};

我看到响应是应该在控制台中的。但是在localhost的JSON输出:3000 / api / accounts不显示更改的JSON对象。

I see that the response is as it should be in the console .. however the JSON output at localhost:3000/api/accounts does not show the altered JSON object.

在Loopback中更改JSON响应/请求的正确方法是什么?

What is the correct way to alter the JSON response / requests in Loopback?

理想情况下,可以将其应用于所有模型。

Ideally in a general way so it can be applied to all Models.

推荐答案

通过使用 DS.RESTAdapter DS.JSONSerializer 像这样:

// app/adapters/application.js

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  host: 'http://loopback-api-host',
  namespace: 'api',
  defaultSerializer: 'JSONSerializer'
});

在Ember Data中,用于与后端数据存储进行通信的逻辑位于适配器中,Ember Data适配器有一些关于REST API应该如何看待的内置假设,如果您的后端约定与这些假设不同,Ember Data可以轻松更改其功能是通过交换或扩展默认适配器。

"In Ember Data, the logic for communicating with a backend data store lives in the Adapter. Ember Data's Adapter has some built-in assumptions of how a REST API should look. If your backend conventions differ from these assumptions Ember Data makes it easy to change its functionality by swapping out or extending the default Adapter."

类似问题:

这篇关于使Loopback API Ember.js兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 20:03