ember.js - pass - ember onclick
Как вводить currentUser во все другие модели пользователей (2)
в моем приложении у меня есть несколько пользователей, которые могут быть друзьями. Теперь я пытаюсь создать функцию, которая получает «friendShipStatus» от текущего зарегистрированного пользователя другому пользователю. Это следующий вопрос из этого: Пересечение обещаний и зависимых вычисленных свойств
/**
* Gives the relation between two User
* 4: has requested your friendship
* 3: Yourself
* 2: Friends
* 1: FriendShip Request
*/
friendShipStatus: function() {
return this.container.lookup('user:current').then(function(user){
if(this.get('friends').contains(user)){
return 2;
} else if(this.get('friendsWithMe').contains(user)){
return 4;
} else if(this.get('myFriends').contains(user)){
return 1;
} else if (this.get('id') === user.get('id')){
return 3;
} else {
return 0;
}
});
}.property('[email protected]')
«Обещание» уже является попыткой, но не работает. Я предпочел бы, чтобы currentUser вводил и наблюдал тогда свойство, что, как только текущий пользователь будет разрешен, свойство изменится. Моя попытка:
Ember.Application.initializer({
name: "currentUser",
initialize: function(container, application) {
var store = container.lookup('store:main');
container.register('user:current', store.find('user', 1), { instantiate: false, singleton: true });
}
});
Ember.Application.initializer({
name: "injectCurrentUser",
after: 'currentUser',
initialize: function(container) {
// container.injection('controller:application', 'currentUser', 'user:current');
container.typeInjection('route', 'currentUser', 'user:current');
container.typeInjection('controller', 'currentUser', 'user:current');
container.typeInjection('model', 'currentUser', 'user:current');
container.injection('user:model', 'currentUser', 'user:current');
}
});
Я уже пробовал это с инъекцией типа и регулярной инъекцией. Но в моем usermodel свойство currentUser всегда не определено.
Как я могу вставить текущего пользователя в мою модель пользователя?
Вы не ожидаете возвращения пользователя из данных ember перед регистрацией. Вероятно, вы захотите отложить готовность к блокировке до тех пор, пока она не вернется. Попробуйте что-то вроде этого:
Ember.Application.initializer({
name: "currentUser",
initialize: function(container, application) {
application.deferReadiness();
container.lookup('store:main').find('user', 1).then(function(user) {
application.register('user:current', user, { instantiate: false, singleton: true });
application.inject('route', 'currentUser', 'user:current');
application.inject('controller', 'currentUser', 'user:current');
application.advanceReadiness();
}, function() {
application.advanceReadiness();
});
}
});
Я не уверен, почему вы хотите вводить в свою модель, для моего маршрута / контроллера достаточно. Также обратите внимание, что это один инициализатор, а не два.
Просто выяснили другое решение, используя услуги ember-cli. Сначала ember g service user
сервиса ember g service user
. Затем введите store
на службу, чтобы вы могли find()
. Затем измените службу со стандартного Object
ObjectProxy
. Наконец, init()
выполняет поиск и устанавливает результат в content
. Вот что у меня есть в конце:
// app/initializers/user-service.js
export function initialize(container, application) {
application.inject('route', 'user', 'service:user');
application.inject('controller', 'user', 'service:user');
application.inject('service:user', 'store', 'store:main');
}
export default {
name: 'user-service',
initialize: initialize
};
,
// app/services/user.js
import Ember from 'ember';
export default Ember.ObjectProxy.extend({
init: function(){
this.set('content', this.store.find('user', 1));
}
});