如何在Ember中处理来自服务器的重定向响应

时间:2014-07-08 13:30:20

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

ember-data 1.0,ember 1.5.1,rails 3.2

如何处理来自服务器的重定向响应?在ember-data 0.13中我做了:

Staas.Adapter = DS.RESTAdapter.extend
  didCreateRecord: (store, type, record, payload) ->
    if payload.redirect
      window.location.replace payload.redirect
      return

    @_super(store, type, record, payload)

但是现在Adapter中没有didCreateRecord方法。我想实现通用解决方案,而不是每个保存承诺。

谢谢。

1 个答案:

答案 0 :(得分:2)

您可以重新打开RESTAdapter并修改所有实例的ajax方法。

DS.RESTAdapter.reopen({
    ajax: function(url, type, hash) {
      var adapter = this;

      return new Ember.RSVP.Promise(function(resolve, reject) {
        hash = adapter.ajaxOptions(url, type, hash);

        hash.success = function( json ) {
          Ember.run(null, resolve, json);
        };

        hash.error = function(jqXHR, textStatus, errorThrown) {
          Ember.run(null, reject, adapter.ajaxError(jqXHR));
        };

        Ember.$.ajax(hash);
      }, "DS: RestAdapter#ajax " + type + " to " + url).then(function(json){
        if(json && json.redirect){
          //redirect here
          alert('redirect');
        }
        return json;
      }, function(jqXHR){
        if(jqXHR.status == 302){  
          //redirect here
          alert('redirect');
        }
        return jqXHR;
      });
    },

  });

示例302状态:http://emberjs.jsbin.com/OxIDiVU/796/edit

示例有效负载:http://emberjs.jsbin.com/OxIDiVU/798/edit