简体   繁体   English

使用Ember.js从发布请求接收服务器响应中的JSON API

[英]Using Ember.js to Receive JSON API in Server Response from a Post Request

I have an API that I interface with by sending a JSON object in the body of a post request. 我有一个API,通过在post请求的主体中发送JSON对象来与之交互。 In return, upon successful authorization the server will respond with a JSON API feed in the body of its post response. 作为回报,在成功授权后,服务器将在其响应后的主体中使用JSON API提要进行响应。

How can I use Ember.js to receive the payload returned from the server as a result of sending the JSON request? 如何通过发送JSON请求使用Ember.js接收从服务器返回的有效负载? I see that Ember Data, and Ember-model allows for the use of headers, but it doesnt look like theres the ability to send a POST body. 我看到Ember Data和Ember模型允许使用标题,但它看起来不像发送POST主体的能力。

Here's an example of the JSON I need to send the server in order to receive the JSON API back in the post response. 这是我需要发送服务器以便在post响应中接收JSON API的JSON示例。

{
    "auth": {
        "type" : "basic",
        "password": "xxx",
        "username": "someone"
    },
    "requestId" : 15,
    "method": {
        "name": "getUserAvailabilityAndInfo",
        "params": {
            "userId" : "000",
            "peopleOnly" : "1"
        }
    }
}

I can't speak authoritatively to ember-data (though I know enough to assert that it certainly supports the HTTP POST verb), except to quote the docs: 我不能权威地说ember-data(虽然我知道足以断言它肯定支持HTTP POST动词),除了引用文档:

Without any configuration, Ember Data can load and save records and their relationships served via a RESTful JSON API, provided it follows certain conventions. 如果没有任何配置,Ember Data可以通过RESTful JSON API加载和保存记录及其关系,前提是它遵循某些约定。

If you need to integrate your Ember.js app with existing JSON APIs that do not follow strong conventions, Ember Data is designed to be easily configurable to work with whatever data your server returns. 如果您需要将Ember.js应用程序与不遵循强约定的现有JSON API集成,则Ember Data可以轻松配置为与服务器返回的任何数据一起使用。

See http://emberjs.com/guides/models 请参见http://emberjs.com/guides/models

The 'certain conventions' that Ember Data refers to above is a bit of a moving target, but the Ember team is close to codifying that definitively (see jsonapi.org). Ember Data上面提到的“某些约定”是一个移动目标,但Ember团队接近于最终编纂(见jsonapi.org)。

Also from that doc: 也来自那个文档:

For simple applications, you can get by using jQuery to load JSON data from a server, then use those JSON objects as models. 对于简单的应用程序,您可以使用jQuery从服务器加载JSON数据,然后将这些JSON对象用作模型。

I'll demonstrate how to do just that. 我将演示如何做到这一点。

The simplest way to get started is to just use Ember's included jQuery.ajax() method anywhere in your ember codebase: 最简单的入门方法是在你的ember代码库中的任何地方使用Ember包含的jQuery.ajax()方法:

App.examplePost = function () {
    return Em.$.ajax('http://example.com/api/serviceXYZ', {
        "type": 'POST', // HTTP method
        "dataType": 'JSON', // type of data expected from the API response
        "data": { // Begin data payload
            "auth": {
                "type" : "basic",
                "password": "xxx",
                "username": "someone"
            },
            "requestId" : 15,
            "method": {
                "name": "getUserAvailabilityAndInfo",
                "params": {
                    "userId" : "000",
                    "peopleOnly" : "1"
                }
            }
        }, // End data payload
        "success": function (data, textStatus, jqXHR) {
            return data;
        },
        "error": function (jqXHR, textStatus, errorThrown) {
            window.console.log(jqXHR);
        }
    });
};

(See the standard jquery ajax() docs for more details on the above.) (有关上述内容的更多详细信息,请参阅标准jquery ajax()文档。)

Some examples of how to actually use something like the above in your ember app: 有关如何在您的ember应用中实际使用上述内容的一些示例:

The "model hook" “模型钩”

In an appropriate route definition, we would override the default model() method: 在适当的路由定义中,我们将覆盖默认的model()方法:

App.ExamplePostRoute = Ember.Route.extend({
    model: function (params) {
        return App.examplePost();
    }
});

To see the model hook in action, you'd navigate to the route path that maps to the 'examplePost' route state via its associated URL ( eg, http:/myemberapp.example.com/#/examplePost ). 要查看模型挂钩的操作,您将导航到通过其关联的URL( 例如,http:/myemberapp.example.com /#/ examplePost )映射到“examplePost”路由状态的路径路径。 Because our ajax call executed by App.examplePost() eventually returns the API data on a fulfilled Promise (see the success() function), the model hook knows to use that response as its model object (and it knows how to do this asynchronously using promises). 因为我们的App.examplePost()执行的ajax调用最终在完成的Promise上返回API数据(参见success()函数),所以模型钩子知道将该响应用作其模型对象(并且它知道如何异步执行此操作)使用承诺)。

A "static object" controller “静态对象”控制器

An even more artificial example would be to override the default setupController() method, also in the route definition. 一个更加人为的例子是覆盖默认的setupController()方法,也在路由定义中。

App.ExamplePostRoute = Ember.Route.extend({
    setupController: function (controller, model) {
        return App.examplePost().then(
            function (data) {
                controller.set(model, data);
            }
        );
    }
});

The setupController route method (which is always called, whether or not you transition to a route state via URL or other transition method) does not know about promises, hence the .then() usage above. 该setupController路线方法(它总是叫,你是否过渡到通过URL或其他过渡方法的路由状态) 知道的承诺,因此以上。那么()的用法。

Again, you'd not normally statically load a literal model every time you enter a route state, but it's a way to get started, and with the Chrome Ember Inspector, will help you to prove that in fact this can work! 同样,每次进入路线状态时,您通常不会静态加载文字模型,但这是一种入门方式,并且使用Chrome Ember Inspector,将帮助您证明实际上这可以工作! Also, jquery and promises are a complicated subject, and in practice if you rolled your own client API code, you'd want to cast jquery's promise object into a standard promise object (see promises.org) via Ember.Deferred.promise() , for example. 此外,jquery和promises是一个复杂的主题,实际上如果你推出了自己的客户端API代码,你需要通过Ember.Deferred.promise()将jquery的promise对象转换为标准的 promise对象(请参阅promises.org)。 , 例如。 This is beyond the scope of this question, but FYI for your near-future explorations. 这超出了这个问题的范围,但是对于您近期的探索,仅供参考。

It's possible to use the ember-ajax service and/or ES2015 request class 可以使用ember-ajax服务和/或ES2015 请求类

This is a newer conventional way (Ember 2.x) in dealing with API requests and responses and thus response payload/data, without relying on ember-data as ember-ajax ver 2 can be used directly and it's meant to replace the Ember.$.ajax API. 这是一种更新的传统方式(Ember 2.x)处理API请求和响应,从而响应有效载荷/数据,而不依赖于ember-data,因为ember-ajax ver 2可以直接使用,它意味着取代Ember.$.ajax API。

Using the ajax service exposed through ember-ajax/services/ajax , one might send requests and handle responses as such: 使用ajax通过公开的服务余烬的Ajax /服务/ AJAX ,一个可以发送请求和处理,因为这样的答复:

import Ember from 'ember';

export default Ember.Controller.extend({
  ajax: Ember.inject.service(),
  actions: {
    someAction(someObject) {
      let payload = { foo: Ember.get(someObject, 'someProperty') };
      this.get('ajax').post('/url', {
        data: payload
      }).then(({ response }) => {
        ...
        // handle response;
      });
    }
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM