【问题标题】:Emberjs - model hook returns null from BelongsTo relationshipEmberjs - 模型挂钩从 BelongsTo 关系返回 null
【发布时间】:2016-01-13 19:01:56
【问题描述】:

我在 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 获取数据。

所以我发帖到:

POST:/api/client/1/phone

我已将转换设置为返回到 phone.index 页面(保存完成后),然后(应该)触发模型挂钩(GET 请求:/api/client/1/phone)并获取(phones.index) 页面的新数据。但由于某种原因,我从 Ember 收到“数据为空”错误。在出现此错误之前,它甚至似乎都没有发出请求。

如果我在 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

【问题讨论】:

  • 你在单独的路线中有这个表格的原因是什么?!这可以很容易地在 client/1 路由中实现。
  • 或者逻辑上是客户端 => /client/edit/1 = (action with form) => /client/view/1
  • @kristjanreinhold 用户单击电话路由中的按钮以显示表单。我基本上是使用 {{link-to}} 来访问表单。

标签: javascript ember.js


【解决方案1】:

我认为您不需要新的路线来显示个人电话的表格。而是在用户点击电话表单时创建一个属性来切换

假设您的模板如下所示

/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}}

控制器/用户/

   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): 
        }
     }

【讨论】:

    猜你喜欢
    • 2016-02-29
    • 2020-05-16
    • 2016-03-31
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多