简体   繁体   中英

Cannot call save a on an ember-data relation

I want to handle a relation in a component/form. It works fine when I create the relation, but it fails when I try to update

import Ember from 'ember';

export default Ember.Component.extend({
  store: Ember.inject.service(),
  init(){
    this._super(...arguments);
    var adresseField=this.get('adresseAttributeField');
    var parent=this.get('parent');
    if (parent.get(adresseField).content==null) {
      this.set('adresse',this.get('store').createRecord('adresse'));
    }else{
      this.set('adresse',parent.get(adresseField));
    }
  },
  actions:{
    saveAdresse(adresse){
      console.log(adresse);
      var parent=this.get('parent');
      var adresseField=this.get('adresseAttributeField');
      adresse.save().then(()=>{
        if(parent.get(adresseField)!=adresse){
          parent.set(adresseField,adresse)
          parent.save()
        }
      }),()=>{
      }
    }
  }
});

The error message occurs when saveAdresse is triggered and the adress is updated:

adresse.save is not a function

When creating the adresse the component works fine.

I think my problem is in the init when I retrieve the existing relation :

this.set('adresse',parent.get(adresseField));

However I cannot identify what's the problem exactly.

The problem here is likely that adresseField is an asynchronous relationship. For this kind of relationship, Ember Data will return what is called a promise proxy object. This is so Ember can access the properties once that relationship resolves. However, methods are not proxying, hence why it is telling you that adresseField does not have the method.

You need to access the resolved relationship in a .then block:

parent.get(adresseField).then(result => {
  this.set("adresse", result);
});

The problem probably lies in the fact that it is an asynchronous relationship. You could solve this by calling .then on the promise and setting the property there, but this could lead to asynchronous side effects. Really by the time you are in the component you want all the data available to you without making async calls.

If it is at all possible, you would be better off loading that data at the route level so that you know it is available at this point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM