【问题标题】:RESTAdapter in EmberJSEmberJS 中的 RESTAdapter
【发布时间】:2013-10-22 14:07:25
【问题描述】:

我是 EmberJs 的新手,我对 Ember 的适配器不太了解。我只是在我的 App.Js 中尝试使用 ember 适配器,然后我得到了这个错误(断言失败:你试图将 adapter 属性设置为DS.Adapter 的实例,它应该是名称或工厂)。我在 App.js 中的 ember 代码是:

//Store
App.Adapter =  DS.RESTAdapter.extend();
App.Store = DS.Store.extend({
    revision: 12,
    adapter: App.Adapter.create()
});
//Models
App.Product = DS.Model.extend({
    name: DS.attr('string'),
    description: DS.attr('string'),
    price: DS.attr('number')
});

// Products Route
 App.ProductsRoute = Ember.Route.extend({
  model: (function() {
      return this.store.find('Product');
  })
});
return App;

【问题讨论】:

    标签: javascript ember.js


    【解决方案1】:

    我认为您误解了设置和配置适配器的方式。

    //
    // Application-wide adapter, everything will use this unless you override it
    //
    
    App.ApplicationAdapter =  DS.RESTAdapter.extend({
      host: 'https://api.example.com'
    });
    
    //
    // Product model, will use ApplicationAdapter
    // 
    
    App.Product = DS.Model.extend({
      name        : DS.attr('string'),
      description : DS.attr('string'),
      price       : DS.attr('number')
    });
    
    //
    // Invoice model, will use fixtures, so specify a different adapter 
    // 
    
    App.InvoiceAdapter =  DS.FixtureAdapter.extend({ /* options */ });
    
    App.Invoice = DS.Model.extend({
      name   : DS.attr('string'),
      amount : DS.attr('number')
    });
    
    //    
    // Routes, these should work as expected
    //
    
    App.ProductRoute = Ember.Route.extend({
      model: function(params) {
        return this.store.find('product', params.id);
      }
    });
    
    App.ProductsRoute = Ember.Route.extend({
      model: function() {
        return this.store.find('product');
      }
    });
    
    App.InvoicesRoute = Ember.Route.extend({
      model: function() {
        return this.store.find('invoice');
      }
    });
    
    return App;
    

    Ember 会根据它们的名称知道要使用哪些模型/路由/等 - 有关详细信息,请参阅 http://emberjs.com/guides/concepts/naming-conventions/

    【讨论】:

      【解决方案2】:

      以这种方式定义商店

      App.Store = DS.Store.extend({
          revision: 12,
          adapter: App.Adapter
      });
      

      没有 create()。

      【讨论】:

        【解决方案3】:

        适配器的主要用途是根据一些约定对数据进行序列化和反序列化,例如构造用于发布或获取数据的 url,然后从响应中构造实际对象。 ember 数据模型使用的默认适配器是 Rest 适配器。

        http://emberjs.com/guides/models/the-rest-adapter/ 了解更多

        要使用与其余适配器不同的适配器,您可以指定其名称,如

        Storm.Store = DS.Store.extend({ adapter: '_ams', });

        【讨论】:

          【解决方案4】:

          试试:

          App.ApplicationAdapter = DS.RESTAdapter.extend();
          

          这对我有用

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-31
            • 2015-05-24
            • 1970-01-01
            • 2023-04-02
            • 1970-01-01
            • 2013-09-09
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多