[英]How to retrieve static data in Ember?
我的一些 model 具有 state 列表的屬性:
東西.js
...
status: DS.attr('number'),
statesValues: {1 : "First",2: "Some Choice", 3: "Nothing"}
...
如何在另一個 ember object 中訪問 Thing model 中的值? 我嘗試導入 model 但我什至不知道正確的導入路徑。
我認為該服務將是一個很好的解決方案,可以在 Ember.js 應用程序中共享 static 數據並在需要時注入它。
// 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()
....
});
您需要使用以下方法之一從商店獲取 model: 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'));
最后我在我的 model 中添加了這個:
export const statusValues ={...}
為了使用它,我根據需要導入它:
import {statusValues} from 'app-name/models/model-name'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.