首页 > 解决方案 > 在 beforeRemote('create' 上存储特定请求的变量并在 afterRemote('create' 上使用它

问题描述

我想在 beforeRemote('create' 上存储特定请求的变量并在 afterRemote('create' 上使用它。我知道我可以将变量存储在模型类变量中,但我担心它将在请求之间共享。

例如:

MyModel.beforeRemote('create', function(ctx, unused, next) {
   // Here i want to store a variable like:

   this.storedValue = "xxx";
}

然后,在这里使用它:

MyModel.afterRemote('create', function(ctx, unused, next) {
console.log(this.storedValue);
}

我将在模型中声明的 this.storedValue 是静态模型还是实例模型?

标签: loopbackjsstrongloop

解决方案


尝试这个:

MyModel.beforeRemote('create', function(ctx, unused, next) {
   // Here i want to store a variable like:

   ctx.hookState.storedValue = "xxx";
}

MyModel.afterRemote('create', function(ctx, unused, next) {

  const storedValue = ctx.hookState && ctx.hookState.storedValue; 
  console.log(storedValue);
}

推荐阅读