我正在尝试在 ember 项目中查找与当前用户关联的帐户。我能够获取用户 ID 并通过 {{account.user.id}}
将其传递给 Handlebars 脚本。然而,我在模型 Hook 中查找具有此用户 ID 的帐户的所有尝试均未成功。
我当前在routes/my-account.js中的模型 Hook :
model (params) {
let accountID = this.store.query('account', { filter: { user: { id:currentUser} } });
console.log(accountID.id);
return this.get('store').findRecord('account', accountID);
}
accountID 作为 ember 类返回,但我似乎无法解析其中的任何数据。我如何从返回的 ember 类中获取 ID,以便将其传递给我的 get 请求?
最佳答案
要从 Ember 对象获取和设置属性,您必须使用 get
和 set
,例如:
console.log(account.get('id'));
更重要的是,您的 .query
将(或至少应该)返回与过滤器匹配的 account
模型数组。它将被包装在一个 promise 中——因为它是一个异步网络调用——所以你需要.then
它。您可能只想获取第一个帐户:
model() {
return this.store.query('account', { filter: { user: { id: currentUser } } })
.then(function(accounts) {
return accounts.get('firstObject');
});
}
如果您有正确的 {json:api},您只需获取 user
,然后从例如获取其 account
关系即可。 /api/users/:id/account
。你的模型钩子(Hook)看起来像:
model() {
return this.store.findRecord('user', currentUser)
.then(function(user) {
return user.get('account');
});
}
关于javascript - 在 ember 中查找属于关系中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44528824/