如何检索 Ember 中的静态数据?
How to retrieve static data in Ember?
我的一些模型有 属性 状态列表:
thing.js
...
status: DS.attr('number'),
statesValues: {1 : "First",2: "Some Choice", 3: "Nothing"}
...
如何在另一个 ember 对象中访问事物模型中的值?
我尝试导入模型,但我什至不知道正确的导入路径。
您需要使用此处介绍的方法之一从商店获取模型:https://guides.emberjs.com/release/models/finding-records/。
现有记录
const myModel = await this.store.findRecord('thing', 1);
console.log(myModel.get('statesValues'));
新记录
const myModel = this.store.createRecord('thing', { /* optional defaults go here, e.g., `status: 2,` */ });
console.log(myModel.get('statesValues'));
最后我在我的模型中添加了这个:
export const statusValues ={...}
为了使用它,我根据需要导入它:
import {statusValues} from 'app-name/models/model-name'
我认为 service 将是跨 Ember.js 应用程序共享静态数据并在需要时注入的好解决方案。
// app/services/static-data.js
import Service from '@ember/service';
import { computed } from '@ember/object'
export default Service.extend({
statesValues: computed(function() {
return { 1: 'First', 2: 'Second', 3: 'Third' };
})
});
然后你可以在你的应用程序、组件、模型、控制器等的任何地方注入它...
// app/models/thing.js
import DS from 'ember-data';
import { inject as service } from '@ember/service';
export default DS.Model.extend({
staticData: service()
....
});
我的一些模型有 属性 状态列表:
thing.js
...
status: DS.attr('number'),
statesValues: {1 : "First",2: "Some Choice", 3: "Nothing"}
...
如何在另一个 ember 对象中访问事物模型中的值? 我尝试导入模型,但我什至不知道正确的导入路径。
您需要使用此处介绍的方法之一从商店获取模型:https://guides.emberjs.com/release/models/finding-records/。
现有记录
const myModel = await this.store.findRecord('thing', 1);
console.log(myModel.get('statesValues'));
新记录
const myModel = this.store.createRecord('thing', { /* optional defaults go here, e.g., `status: 2,` */ });
console.log(myModel.get('statesValues'));
最后我在我的模型中添加了这个:
export const statusValues ={...}
为了使用它,我根据需要导入它:
import {statusValues} from 'app-name/models/model-name'
我认为 service 将是跨 Ember.js 应用程序共享静态数据并在需要时注入的好解决方案。
// app/services/static-data.js
import Service from '@ember/service';
import { computed } from '@ember/object'
export default Service.extend({
statesValues: computed(function() {
return { 1: 'First', 2: 'Second', 3: 'Third' };
})
});
然后你可以在你的应用程序、组件、模型、控制器等的任何地方注入它...
// app/models/thing.js
import DS from 'ember-data';
import { inject as service } from '@ember/service';
export default DS.Model.extend({
staticData: service()
....
});