模型钩子从BelongsTo关系返回null

Emberjs - model hook returns null from BelongsTo relationship

本文关键字:关系 返回 null BelongsTo 模型      更新时间:2023-09-26

我在new-phone路由中有一个表单,它填充了一个电话模型。此模型与客户端有belongsTo关系。

App.Router.map(function() {
    this.resource("client", { path: "/client/:id" }, function(){
        this.resource("phone", function(){
            this.route("new-phone")
        })
    })
})
App.Client = DS.Model.extend({
    name: DS.attr(),
    phone: DS.belongsTo("Phone", { async: true })
});
App.Phone = DS.Model.extend({
    name: DS.attr(),
    model: DS.attr(),
    year: DS.attr()
});  

当我完成表单时,服务器的响应会正确返回新创建的记录。

我正在从JSON驱动的API获取数据。

所以我发布到:

:/api/客户/1/手机

我已经设置了切换回电话。索引页(保存完成后),然后(应该)触发模型钩子(GET request:/api/client/1/phone)并获取(phones.index)页的新数据。但出于某种原因,我从Ember得到一个'data is null'错误。在此错误出现之前,它甚至没有发出请求。

如果我在Ember应用程序之外使用HTTP请求程序,数据就会出现。

App.ClientRoute = Ember.Route.extend({
    model: function(){
        return this.store.find("client", 1)
    }
});
App.PhoneIndexRoute = Ember.Route.extend({
    model: function(){
        return this.modelFor("client").get("phone").then(function(data){
            //Reload to manually get new data
            return data.reload();
        });
    }
})

这是我正在使用的Ember版本:

DEBUG: Ember      : 1.8.1
DEBUG: Ember Data : 1.0.0-beta.11
DEBUG: Handlebars : 1.3.0
DEBUG: jQuery     : 1.10.2

我认为你不需要一个新的路由来显示一个表单的人的电话。相反,创建一个属性,当用户单击电话表单

时进行切换

假设你的模板是这样的

/user/1. hbs

{{model.user_name}} {{model.first_name}}
{{model.phone.number}}
{{#if showPhoneForm}}
    <div class="form">
          {{input value=model.phone.number placeholder="phone nr"}}
    </div>
    <div class="button" {{action "saveUser"}}> Save </button> // Save form data, hide user form, updaet user phone data
{{else}}
    <div class="button" {{action "makePhoneForm"}}> Add phone </button> // Create form for user
{{/if}}

控制器/user/

   showPhoneForm: false,
   actions: {
        makePhoneForm: function() {
          this.set('showPhoneForm', true); 
        },
        saveUser: function() {
          this.get('model.phone').then(function(phoneRecord) {
            phoneRecord.save().then(function(){
              this.set('showPhoneForm', false);
            }.bind(this): 
        }
     }