How to handle 404 of Ember Data in route?

后端 未结 3 1530
借酒劲吻你
借酒劲吻你 2021-02-15 16:42

In my route I have a method that tries to request a list of models from the server

 model: ->
    App.MyModel.find
      projectId: (@modelFor \"project\").id         


        
3条回答
  •  攒了一身酷
    2021-02-15 17:13

    Incidentally, the "new" BasicAdapter was just released now. The question for me was, will this make things easier to handle 404 errors.

    Approach #1

    My first approach - similar to what Christopher was suggesting - was to add an additional field containing the HTTP status.

      status: DS.attr("number");
    

    And then I used this AJAX call:

    $.getJSON(url, data).then(null, function(xhr) {
      return {
        id: id,
        statusCode: xhr.status
      };
    }).always(function(data) {
      return process(data).load();
    });
    

    What this does is to transform the error response (xhr) to a hash containing the requested id and the status code. Finally, the successful result or the failed hash are passed to the store.

    This kind of works, but isn't very practical: When you show a list of all model instances those "mock" instances have to be filtered out manually.


    Approach #2

    Another idea was to create a special error model.

    App.Error = App.Model.extend({
      status: DS.attr("number")
    });
    

    And the according query:

    $.getJSON(url, data).then(null, function(xhr) {
      return App.store.load(App.Error, {}, {
        id: 0,
        status: xhr.status
      });
    }).done(function(data) {
      return process(data).load();
    });
    

    This will load and create a new instance of the error model and put it into the store.

    The problem with this is that Ember wasn't really "accepting" this. The application just stopped routing, doing nothing anymore. So this seems like a dead end as well :(

提交回复
热议问题