继承模型的远程方法未显示在环回资源管理器中

时间:2015-07-21 13:10:12

标签: loopbackjs strongloop

我在环回中继承了一个模型 -

{
    "name": "MyModel",
    "base": "AnotherModel",
    "idInjection": false,
    "properties": {
      "value": {
        "type": "String"
      },
      "display": {
        "type": "String"
      }
    },
    "validations": [],
    "relations": {},
    "acls": [],
    "methods": []
}

虽然我可以从AnotherModel文件中调用MyModel.js的所有远程方法。但是,AnotherModel的远程方法没有出现在我的资源管理器上。如何让我继承的模型的所有远程方法显示在资源管理器中?

2 个答案:

答案 0 :(得分:4)

发生这种情况的原因是,当您调用AnotherModel.remoteMethod时,它只为该模型注册了该远程方法,而不是基于此模型的模型。要为所有基于AnotherModel的模型调用它,您可以执行以下操作:

var originalSetup = AnotherModel.setup;
AnotherModel.setup = function() { // this will be called everytime a 
  // model is extended from this model.

  originalSetup.apply(this, arguments); // This is necessary if your 
  // AnotherModel is based of another model, like PersistedModel.

  this.remoteMethod('yourMethod', {
    ..
  });
};

我从here学到了这一点,并且还检查了persistedModel如何在所有基于它的模型中使用它的远程方法。

还要确保基本模型是公开的due to this issue

答案 1 :(得分:0)

你应该使用setup()来"暴露" AnotherModels'功能。 http://loopback.io/doc/en/lb2/Extending-built-in-models.html#setting-up-a-custom-model 然后在设置部分添加您的远程方法,如下所述:http://loopback.io/doc/en/lb2/Remote-methods#example

以下是示例:(它也可以应用于静态函数)

// AnotherModel.js
module.exports = function (AnotherModel) {
    ...
    // suppose you have two functions to inherit 'function1' and 'function2'
    AnotherModel.prototype.function1 = function() {...}
    AnotherModel.function2 = function() {...}
    // The loopback.Model.extend() function calls setup() 
    // so code you put in setup() will automatically get 
    // executed when the model is created.  
    var originalSetup = AnotherMoldel.setup;
    AnotherMoldel.setup = function() {
        // call the original setup!
        originalSetup.apply(this, arguments);
        // 'this' will points to MyModel during MyModel setup
        // first param should match with function name
        this.remoteMethod('function1', {
            accepts: {...}, 
            returns: {...}, 
            http: {...}});
        this.remoteMethod('function2', {
            accepts: {...}, 
            returns: {...}, 
            http: {...}});
    }
}

它将显示在API资源管理器中。

我希望它有所帮助,如果你找到了另一个解决方案,请告诉我! (因为这篇文章超过一年)

干杯