javascript - 如何在 route 使用服务属性?

标签 javascript node.js ember.js ember-data

我有一个处理用户身份验证并通过模型获取用户数据的服务。它获取的数据之一是饮食计划的开始日期。我想使用此日期来计算一个数字:自程序启动以来的天数,因此我可以使用该数字来查询从 CMS 提取内容的不同模型。

除了模板之外,我无法在任何地方访问该号码。

这是仪表板的 Controller

import Ember from 'ember';

export default Ember.Controller.extend({

  authManager: Ember.inject.service('session'),
    });

这是模板

{{#if authManager.currentUser.activeCleanse}}
  You are on a cleanse that starts 
{{authManager.currentUser.cleanse_start}}
  {{else}}
  You are not on a cleanse.
{{/if}}

以上所有代码都有效,但是当我在 Controller 中尝试类似的操作时:

  activeCleanse: Ember.computed( function(){
    return this.get('authManager.currentUser').then( (user) => {
    return user.cleanse_active;
    }.bind(this))
  }),

  startDate: Ember.computed( function(){
    return this.get('authManager.currentUser').then( (user) => {
    return user.cleanse_start;
    }.bind(this))
  })

并将模板替换为:

{{#if activeCleanse}}
  You are on a cleanse that starts {{startDate}}
  {{else}}
  You are not on a cleanse.
{{/if}}

它不会响应 activeCleanse 为 false(模板似乎只是检查其存在),并且日期标记仅显示 [object Object]

我实际上正在尝试获取 Controller 中的日期,以便我可以操纵它作为参数之一传递给仪表板路线,该路线根据特定日期获取模型:

仪表板路线

import Ember from 'ember';

export default Ember.Route.extend({

  model() {
    return this.get('store').queryRecord('cleanse-post', {
      filter: {
        tag: 'day-1'
        }
      });
    },

});

我希望能够根据日期的计算动态设置过滤器的标签。

如有任何帮助,我们将不胜感激。我觉得我一直在兜圈子,而且不知道该尝试什么。

最佳答案

  1. activeCleanse它的计算属性依赖于authManager.currentUser,所以你的计算属性格式应该是这样的
     activeCleanse: Ember.computed('authManager.currentUser',function(){
      //return the result
     }),

There is no need for bind(this) since that computed property will be called with particular context, in your example this would be controller.

  1. Currently your computed property is returning Promise, computed property is not promise aware. you can try returning DS.PromiseObject to make it work.
    activeCleanse:Ember.computed(function(){
        return DS.PromiseObject.create({
          promise: this.get('authManager.currentUser').then( (user) => {
            return user.cleanse_start;
          })
      })

In your case, I would say you can use setupController hook on the route, where you can set activeCleanse property,

this.get('authManager.currentUser').then( (user) => {
  this.set('activeCleanse,user.cleanse_active);
});

关于javascript - 如何在 route 使用服务属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45426083/

相关文章:

javascript - 变量赋值中操作数的说明

javascript - 我的 ng-view 与 index.html 页面 angularjs 无限循环

node.js - 使用 sails js 多次发出 Socket IO(等于连接的客户端数量)

node.js - 生产环境中的 Node Express 路径不匹配 (Heroku)

javascript - 我如何在 Ember 应用程序中使用 Glimmer 组件?

javascript - 用户控制范围内的全局 JS 变量?

javascript - 如何打印React深层结构的单个div

javascript - Mongoose:查找、修改、保存

ember.js - Sinon 模拟对象不包含顶层原始对象的函数

javascript - Ember 更新数组中的对象