【问题标题】:Meteor.js: access Session variable from RouteController waitOnMeteor.js:从 RouteController waitOn 访问 Session 变量
【发布时间】:2015-10-24 12:30:06
【问题描述】:

我需要在我的流星应用程序的waitOn 函数中从RouteController 访问会话变量,我在模板的onCreated 块上设置了一个会话变量:

Template.practicalQuestionForm.onCreated ->
    Session.set 'domId', Random.id()

然后我需要从我的控制器访问那个会话变量Session.get 'domId',看看waitOn:

@testsAddQuestionController = testsQuestionsController.extend
  template: ->
    qType = Router.current().params.type
    if qType == 'practical'
      'practicalQuestionForm'
    else if qType == 'mcq'
      'mcqQuestionForm'
  waitOn: ->
    console.log Session.get 'domId'
    Meteor.subscribe 'currentSessionUploads', Session.get 'domId'
  data: ->
    questions: TestQuestions.find()  
    test: Tests.findOne slug: this.params.slug
    previous: TestQuestions.find({}, sort: createdAt: 1, limit: 1).fetch().pop()

但是我只收到undefined 有人可以告诉我这是否可能吗?如果不是,您可以向我建议其他替代方案吗?

提前致谢。

【问题讨论】:

    标签: session meteor coffeescript iron-router


    【解决方案1】:

    如果您想在您的waitOn 函数中使用Session,您需要确保此代码将在客户端上执行。

    例如:

    waitOn: function() {
      var domId = undefined;
      if(Meteor.isClient) {
        domId = Session.get('domId');
      }
      return Meteor.subscribe('currentSessionUploads', domId);
    }
    

    请注意,您需要检查 domId 在您的出版物(服务器端)中是否未定义。

    您还必须检查您的 Session 变量是否尚未定义,否则您将获得无限循环并且您的控制器会发疯:

    Template.practicalQuestionForm.onCreated ->
        if not Session.get 'domId'
            Session.set 'domId', Random.id()
    

    【讨论】:

    • 谢谢!我会测试它并回复。提前致谢!
    • 嗨,我有一个问题,waitOn 进入无限循环,所以模板没有加载,我在运行 palication 时检查了 domId 会话变量,它生成并生成随机 id 就像疯狂的。任何想法'
    • 嗯,这可能归因于您的onCreated 模板处理程序。如果您在 onBeforeAction 函数中生成 domId 会怎样?
    • 您好,非常感谢,我只需要检查尚未定义的 Session 变量,我在 onCreated 函数中添加了一个 if 语句,哇哦,我用这个细节编辑了你的答案。 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    相关资源
    最近更新 更多