【问题标题】:Why doesn't calling this server method work in Meteor?为什么在 Meteor 中调用此服务器方法不起作用?
【发布时间】:2014-01-09 17:56:27
【问题描述】:

我的 Meteor 项目的 server/server 目录中有一个名为 authServices.coffee 的文件。它具有以下函数定义,后跟Meteor.methods 调用:

 isAuthorized = () ->
    # note that at this point there is ever to be but one authorized user
    authorized = Assets.getText('authorizedUsers').trim()
    this.userId.trim() is authorized

这不起作用——也就是说,调用Meteor.call 'getKey'会返回undefined

Meteor.methods(
    isAuthorized : isAuthorized
    getKey : () -> 
    if isAuthorized()
        Assets.getText('Key')
)

但如果我在上述getKey 中内联isAuthorized,它会返回true(给定正确的输入)

我猜这是this 对这些对象的行为方式的函数,但无法完全掌握它。

【问题讨论】:

  • 除了发布函数和方法之外,您不必在任何地方使用 Meteor.userId 代替 this.userId 吗?
  • this 中的Meteor.userId 更改为authorizedUsers 我得到throw new Error("Meteor.userId can only be invoked in method calls. Use this.userId in publish functions."); // 17

标签: javascript coffeescript meteor


【解决方案1】:

函数isAuthorized和方法getKey有不同的上下文。最简单的解决方案就是像这样实现getKey

getKey: ->
  if Meteor.call 'isAuthorized'
    Assets.getText 'Key'

或者,您可以手动使用callapply 来传递this,或者您可以将@userId 作为参数传递给isAuthorized 函数。

风格要点:使用 CS 时,如果函数不带参数,则不需要空括号。

【讨论】:

  • 我不需要需要 'em...但是有'em'看起来更好。
【解决方案2】:

这会是一个选择吗?

isAuthorized = (userId) ->
    # note that at this point there is ever to be but one authorized user
    authorized = Assets.getText('authorizedUsers').trim()
    userId.trim() is authorized

Meteor.methods(
    isAuthorized : () -> 
        isAuthorized(this.userId)
    getKey : () -> 
        if isAuthorized(this.userId)
            Assets.getText('Key')
)

【讨论】:

  • 是的,这实际上是我最终实施的地方。我正在寻找对this 及其在此处的行为方式的良好解释。
猜你喜欢
  • 2014-12-08
  • 2016-02-18
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 1970-01-01
  • 2020-12-27
  • 2017-09-25
  • 2021-03-12
相关资源
最近更新 更多