Ember-Data:如何“映射”工作 [英] Ember-Data: How do "mappings" work

查看:82
本文介绍了Ember-Data:如何“映射”工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用ember + emberdata + router + asp.net web api放在一起。大部分似乎都可以工作,但是当我的模型适配器使用ember-data尝试 findAll 时,我会遇到一个错误消息。

I'm currently trying to put something together with ember + emberdata + router + asp.net web api. Most of it seem to work, however I stuck in an error message I get when ember-data tries to findAll through the adapter for my models.

在我的后端我有一个这样的模型(C#):

In my backend I have a model like this (C#):

public class Genre {
    [Key]
    public int Id { get; set; }
    [Required]
    [StringLength(50, MinimumLength=3)]
    public string Name { get; set; }
}

在我的应用程序中,我使用ember-data代表它: / p>

Which in my app I represent it like this using ember-data:

App.Genre = DS.Model.extend({
    id: DS.attr("number"),
    name: DS.attr("string")
}).reopenClass({
    url: 'api/genre'
});

我还在我的应用程序中使用RESTAdapter定义了一个Store:

I have also a Store defined in my App using the RESTAdapter like so:

App.store = DS.Store.create({
    revision: 4,
    adapter: DS.RESTAdapter.create({
        bulkCommit: false
    })
});

商店在我的控制器中使用如下:

And the store is used in my controller as below:

App.GenreController = Ember.ArrayController.extend({
    content: App.store.findAll(App.Genre),
    selectedGenre: null
});

路由器定义为

App.router = Em.Router.create({
    enableLogging: true,
    location: 'hash',
    root: Ember.Route.extend({
        //...

        genre: Em.Route.extend({
            route: '/genre',
            index: Ember.Route.extend({
                connectOutlets: function (router, context) {
                    router.get('applicationController').connectOutlet('genre');
                }
            })
        }),

        //...
    })
})

当我运行我的应用程序时,我得到以下消息,每个对象具有相同的结构:

When I run my application, I get the following message for every object that has this same structure:


未捕获错误:断言失败:您的服务器使用
键0返回散列,但您没有映射

Uncaught Error: assertion failed: Your server returned a hash with the key 0 but you have no mappings

为了引用,这里是json服务是returni ng:

For reference, here's the json the service is returning:

[
  {
    "id": 1,
    "name": "Action"
  },
  {
    "id": 2,
    "name": "Drama"
  },
  {
    "id": 3,
    "name": "Comedy"
  },
  {
    "id": 4,
    "name": "Romance"
  }
]

我无法确切地知道问题是什么,提到我需要映射,我想知道:

I cannot tell exactly what the problem is and since the assertion is mentioning that I need mapping, I'd like to know:


  1. 这个映射以及如何用它。

  2. 由于返回的json是一个数组,我应该在我的应用程序中使用不同类型的控制器,或者在使用这种类型的json的ember-数据?还是应该更改服务器中的JsonFormatter选项?

  1. What this mapping is and how to use it.
  2. Since the returned json is an array, should I be using a different type of controller in my app ,or is there anything I should know about when working with this type of json in ember-data? or should I change the JsonFormatter options in the server?

欢迎任何帮助。

我可以添加更多信息你觉得这还不足以理解这个问题。

I can definitely add more information if you feel this isn't enough to understand the problem.

编辑:我已经在后台改变了一些东西,现在我的 findAll()服务器中的等效操作将输出序列化为以下json:

EDIT: I've changed a few things in my backend and now my findAll() equivalent action in the server serializes the the output as the following json:

{
  "genres": [
      { "id": 1, "name": "Action" },
      { "id": 2, "name": "Drama" },
      { "id": 3, "name": "Comedy" },
      { "id": 4, "name": "Romance" }
   ]
}

但是我仍然无法让它在客户端填充我的模型和我的错误消息已经更改为:

But I still can't get it to populate my models in the client and my error message has changed to this:


未捕获错误:断言失败:您的服务器返回了一个带有
密钥类型的哈希值,但是没有映射

Uncaught Error: assertion failed: Your server returned a hash with the key genres but you have no mappings

不知道还有什么可能做错了。

Not sure what else I might be doing wrong.

方法tha这个例外是 sideload 并检查这样的映射:

The method that throws this exception is sideload and checks for the mappings like this:

sideload: function (store, type, json, root) {
        var sideloadedType, mappings, loaded = {};

        loaded[root] = true;

        for (var prop in json) {
            if (!json.hasOwnProperty(prop)) { continue; }
            if (prop === root) { continue; }

            sideloadedType = type.typeForAssociation(prop);

            if (!sideloadedType) {
                mappings = get(this, 'mappings');
                Ember.assert("Your server returned a hash with the key " + prop + " but you have no mappings", !!mappings);
//...

此调用 sideloadedType = type。 typeForAssociation(prop); 返回 undefined 然后我收到错误消息。方法 typeForAssociation()检查'associationsByName'键,返回一个空的 Ember .MAP

This call sideloadedType = type.typeForAssociation(prop); returns undefined and then I get the error message. The method typeForAssociation() checks for the for 'associationsByName' key which returns an empty Ember.Map.

目前还没有解决这个问题。

Still no solution for this at the moment.

顺便说一下

By the way...

我的动作现在是这样的:

My action is now like this:

    // GET api/genres
    public object GetGenres() {
        return new { genres = context.Genres.AsQueryable() };
    }

    // GET api/genres
    //[Queryable]
    //public IQueryable<Genre> GetGenres()
    //{
    //    return context.Genres.AsQueryable();
    //}

我不得不删除由 json.NET ,因为我找不到配置选项来生成一个json输出,如Ember-Data所期望的(如 {resource_name: [json,json,...]} )。这样做的副作用是我已经失去了内置的OData支持,但我想保留它。有没有人知道如何配置它来为集合生成不同的json?

I had to remove the original implementation which gets serialized by json.NET as I could not find config options to produce a json output as Ember-Data expects ( as in {resource_name : [json, json,...]}). Side effect of this is that I've lost built-in OData support, but I'd like to keep it. Does anyone know how could I configure it to produce different json for a collection?

推荐答案

可以在DS.RESTAdapter中定义映射。我想你可以尝试定义这样的东西:

The mapping can be defined in the DS.RESTAdapter. I think you could try to define something like this:

App.Store = DS.Store.extend({
  adapter: DS.RESTAdapter.create({
    bulkCommit: true,
    mappings: {
      genres: App.Genre
    },
    // you can also define plurals, if there is a unregular plural
    // usually, RESTAdapter simply add a 's' for plurals.
    // for example at work we have to define something like this
    plurals: {
      business_process: 'business_processes' 
      //else it tries to fetch business_processs
    }
  }),
  revision: 4
});

希望这可以解决您的问题。

Hope this resolves your problem.

更新:

Update:

此时,这个没有很好的记录,我不记得我们是否找到了我们自己阅读代码,或者也许Tom Dale指出了这一点。

无论如何,这里是复数
对于映射,我认为我们被驱动与你相同的错误,我们试过,汤姆向我们介绍了这一点。

At this time, this is not well documented, I don't remember if we found it by ourself reading the code, or perhaps Tom Dale pointed on it.
Anyway, here is the point for plurals For the mappings, I think we were driven by the same error as you, and either we tried, either Tom teached us about this.

这篇关于Ember-Data:如何“映射”工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆