Uncaught TypeError: Cannot read property 'createRecord' of undefined

Uncaught TypeError: Cannot read property 'createRecord' of undefined

我试过用很多不同的方式编写这段代码,但是 returns 这个错误:

Uncaught TypeError: Cannot read property 'createRecord' of undefined

App.StackFormComponent = Ember.Component.extend({
    init: function() {
        this.set('stack', Ember.Object.create());
    },

    actions: {
        submit: function() {

            var newStack = this.store.createRecord('stack', {
                title: this.get('stack.title'),
                location: this.get('stack.location'),
                date: new Date().getTime(),
                details: this.get('stack.details'),
            });

            newStack.save();
        },

        cancel: function() {
            this.sendAction('cancel');
        }
    }
});


App.Stack = DS.Model.extend({
    title: DS.attr('string'),
    location: DS.attr('string'),
    date: DS.attr('number'),
    details: DS.attr('string')
});

不幸的是,类似问题的答案没有帮助。有什么想法吗?

Ember 将 store 注入路由和控制器,而不是组件,所以这是你的问题。

您可以继续将 store 注入您的组件内部初始化程序,如下所示:

Ember.onLoad('Ember.Application', function(Application) {
  Application.initializer({
    name: "injectStoreIntoMyComponent",
    after: "store",
    initialize: function(container, application) {      
      application.inject('component:good-test-comp', 'store', 'store:main');
    }
  });
});

工作示例here

将存储注入组件不是一个好的设计。您可以将其作为参数传递 {{my-component store=store}}.

在组件中注入存储不是好的设计。相反,我们需要将数据发送到组件并发送操作以与数据通信。如果您仍想将其作为特例包括在内,那么您可以简单地说,

store: Ember.inject.service()