带有幻影的EmberJS没有完全填充记录

时间:2017-06-02 16:28:56

标签: ember.js ember-data ember-cli ember-cli-mirage

我有一个Ember模型,设有海市蜃楼和一个序列化器。当我向模型中添加一些新字段时,尽管它们位于有效载荷中,它们永远不会被填充:

serializers/application.js

....
normalizeArrayResponse(store, primaryModelClass, payload, id, requestType) {
        const payloadTemp = {};
        const rootKey = Ember.String.pluralize(primaryModelClass.modelName);
    payload.properties.forEach((property, index) => {
    //  in here, property["property_type"] returns the correct value based off 
     ///the fixtures in mirage. Afterwards, property.get("property_type") is  always undefined
            payload.properties[index].featured_image = property["embedded"]["wp:featuredmedia"]
    });
        //payloadTemp[rootKey] = payload;
        return this._super(store, primaryModelClass, payload, id, requestType);
    },

models/property.js

export default Model.extend({
  date: attr('date'),
  slug: attr('string'),
  title: attr(),
  excerpt: attr(),
  department: attr('string'),
  latitude: attr('string'),
  address_street: attr('string'),
  address_two: attr('string'),
  address_three: attr('string'),
  address_four: attr('string'),
  address_postcode: attr('string'),
  features: attr('string'),
  feature_1: attr('string'), //new
  feature_2: attr('string'), //new
  feature_3: attr('string'), //new
  feature_4: attr('string'),  //new
  longitude: attr('string'),
  price: attr('string'),
  price_formatted: attr('string'),
  currency: attr('string'),
  tenure: attr('string'),
  property_type: attr('string'), //new
  bedrooms: attr('string'),
  bathrooms: attr('string'),
  parking: attr('string'),
  reception_rooms: attr('string'),
  featured_image: attr()
});

示例夹具:

"id": 20829,
"date": "2017-05-22T16:31:42",
"date_gmt": "2017-05-22T16:31:42",
"guid": {
"rendered": "http://www.example-estates.co.uk/property/goldstone-crescent-dunstable/"
},
"modified": "2017-05-25T16:00:04",
"modified_gmt": "2017-05-25T16:00:04",
"slug": "goldstone-crescent-dunstable",
"status": "publish",
"type": "property",
"link": "http://www.example-estates.co.uk/property/goldstone-crescent-dunstable/",
"title": {
"rendered": "Goldstone 2 Crescent DUNSTABLE"
},
"excerpt": {
"rendered": "<p>NO UPPER CHAIN &#8211; A THREE BEDROOM EXTENDED SEMI DETACHED HOUSE LOCATED TO THE EAST OF TOWN THAT FEATURES, CLOAK/SHOWER ROOM, UTILITY ROOM/STUDY, LANDSCAPED GARDENS AND GARAGE WITH AMPLE PARKING.</p>\n",
"protected": false
},
"template": "",
"department": "residential-sales",
"address_street": "",
"address_two": "",
"address_three": "Dunstable",
"address_four": "",
"address_postcode": "LU5 4QU",
"latitude": "51.8936687",
"longitude": "-0.5047035",
"price": "325000.00",
"price_formatted": "&pound;325,000",
"currency": "",
"price_qualifier": "",
"sale_by": "",
"tenure": "Freehold",
"deposit": "",
"furnished": "",
"available_date": "",
"bedrooms": "3",
"bathrooms": "",
"reception_rooms": "1",
"property_type": "Semi-Detached House",
"parking": "Garage and Driveway, Parking For 2 Cars",
"outside_space": "",
"featured": "",
"availability": "For Sale",
"marketing_flags": "",
"features": [
"NO UPPER CHAIN",
"A THREE BEDROOM EXTENDED",
"SEMI DETACHED HOUSE",
"LOCATED TO THE EAST OF TOWN",
"CLOAK/SHOWER ROOM",
"UTILITY ROOM/STUDY",
"LANDSCAPED GARDENS",
"GARAGE WITH AMPLE PARKING",
"GAS FIRED CENTRAL HEATING",
"DOUBLE GLAZING"
],
"feature_1": "A THREE BEDROOM EXTENDED",
"feature_2": "SEMI DETACHED HOUSE",
"feature_3": "LOCATED TO THE EAST OF TOWN",
"feature_4": "CLOAK/SHOWER ROOM",
"description": "<p class=\"room\">ACCOMMODATION COMPRISES: Etended entrance hall, utility/study, cloak/shower room, large kitchen/dining room, large lounge to the rear of the property overlooking landscaped private garden, large landing with three generous bedrooms and bathroom, driveway, ample parking and gardens.\n                </p>\n                ",
"office": {
"name": "Dunstable Office",
"address": "20 West Street Dunstable Bedfordshire, LU6 1SX",
"telephone_number": "01582 661112",
"email_address": "sales@example-estates.co.uk"
},

normalizeArrayResponse函数中,检查property.property_type循环中是否存在payload.properties.forEach,但是一旦它成为记录,首先创建模型后添加的字段(用{突出显示) {1}}始终未定义(例如//new)。

2 个答案:

答案 0 :(得分:1)

您是否尝试使用normalize代替normalizeArrayResponse?我用它来添加一些属性,它对我来说很好。顺便说一句,您确定需要修改序列化程序中的有效负载吗?我建议只有在你无法控制后端时才这样做。否则最好修改后端以与ED兼容。

此外,在您的代码中,我看到您尝试为featured_image分配值property["embedded"]["wp:featuredmedia"]。但是我没有在你的夹具中看到这样的属性。这可能会导致致命错误,从而中断normalizeArrayResponse方法的执行。我建议检查浏览器控制台是否有错误并检查你的夹具。

答案 1 :(得分:1)

我假设你的 mirage / serializers / application.js 正在使用RESTSerializer,

import { RestSerializer } from 'ember-cli-mirage';
export default RestSerializer.extend({});

请确保您在 app / serializers / application.js中扩展DS.RESTSerializer

  1. 响应数据正在删除_并使其成为camelCased密钥。因此,如果你定义了property_type,那么海市蜃楼就会用propertyType回复它,所有数据都与RESTSerializer格式一致,请看这个
  2. console.log({"id":"20829","date":"2017-05-22T16:31:42","dateGmt":"2017-05-22T16:31:42","guid":{"rendered":"http://www.example-estates.co.uk/property/goldstone-crescent-dunstable/"},"modified":"2017-05-25T16:00:04","modifiedGmt":"2017-05-25T16:00:04","slug":"goldstone-crescent-dunstable","status":"publish","type":"property","link":"http://www.example-estates.co.uk/property/goldstone-crescent-dunstable/","title":{"rendered":"Goldstone 2 Crescent DUNSTABLE"},"excerpt":{"rendered":"<p>NO UPPER CHAIN &#8211; A THREE BEDROOM EXTENDED SEMI DETACHED HOUSE LOCATED TO THE EAST OF TOWN THAT FEATURES, CLOAK/SHOWER ROOM, UTILITY ROOM/STUDY, LANDSCAPED GARDENS AND GARAGE WITH AMPLE PARKING.</p>\n","protected":false},"template":"","department":"residential-sales","addressStreet":"","addressTwo":"","addressThree":"Dunstable","addressFour":"","addressPostcode":"LU5 4QU","latitude":"51.8936687","longitude":"-0.5047035","price":"325000.00","priceFormatted":"&pound;325,000","currency":"","priceQualifier":"","saleBy":"","tenure":"Freehold","deposit":"","furnished":"","availableDate":"","bedrooms":"3","bathrooms":"","receptionRooms":"1","propertyType":"Semi-Detached House","parking":"Garage and Driveway, Parking For 2 Cars","outsideSpace":"","featured":"","availability":"For Sale","marketingFlags":"","features":["NO UPPER CHAIN","A THREE BEDROOM EXTENDED","SEMI DETACHED HOUSE","LOCATED TO THE EAST OF TOWN","CLOAK/SHOWER ROOM","UTILITY ROOM/STUDY","LANDSCAPED GARDENS","GARAGE WITH AMPLE PARKING","GAS FIRED CENTRAL HEATING","DOUBLE GLAZING"],"feature1":"A THREE BEDROOM EXTENDED","feature2":"SEMI DETACHED HOUSE","feature3":"LOCATED TO THE EAST OF TOWN","feature4":"CLOAK/SHOWER ROOM","description":"<p class=\"room\">ACCOMMODATION COMPRISES: Etended entrance hall, utility/study, cloak/shower room, large kitchen/dining room, large lounge to the rear of the property overlooking landscaped private garden, large landing with three generous bedrooms and bathroom, driveway, ample parking and gardens.\n                </p>\n                ","office":{"name":"Dunstable Office","address":"20 West Street Dunstable Bedfordshire, LU6 1SX","telephone_number":"01582 661112","email_address":"sales@example-estates.co.uk"}});

    1. payload.properties[0].property是普通的对象,它没有get方法,因此property.get("property_type")会显示.get is not function错误。

    2. 您可以直接操作payload并将其返回。您无需介绍tempPayload

    3.     import Ember from 'ember';
          import DS from 'ember-data';    
          export default DS.RESTSerializer.extend({
              normalizeArrayResponse(store, primaryModelClass, payload, id, requestType) {
                  payload.properties.forEach((property, index) => {
                      property['featured_image '] = "new value";
                  });
                  return this._super(store, primaryModelClass, payload, id, requestType);
              }
          });