聚合物计算属性的空值

Empty value on Polymer computed attribute

我试图在 Polymer 中使用计算属性,但我总是得到一个空值。在本例中,我的自定义元素中有一个名为数据图的属性。我向服务器发出 post 请求,获取 JSON 文件,计算结果然后显示。这是我的自定义元素:

<dom-module id="cost-card">
  <template>
    <style>
      p.datos3{
        color: #10cebc;
        text-align: center;
        font-size: 22px;
        margin-top: 0px;
      }
    </style>  
    <p class="datos3">{{datagraph}}</p>  
  </template>
  <script>
    Polymer({
      is: "cost-card",

      properties:{
    usr:{
      type: Number,
      value: 2
    },
    command:{
      type: String,
      value: "SP_GetCostoCampania"
    },  
    datagraph:{
      type: Number,
      computed: 'getCost(command,usr)'
    }
  },

      getCost: function(command,usr){

        var options = {
          hostname: 'localhost',
          path: '/',
          port: 8081,
          secure: false,
          method: 'POST',
          headers: {
            'x-powered-by': 'HTTPClient.js'
          },
          'Content-Type': 'application/json'
        }

        var innerCost;

        var example1 = new HTTPClient(options);
        example1.post("/executeGraph1?command="+ command + "&param1=" + usr, function (err, res, body) {

          body = JSON.parse(body);

          innerCost = body[0].price * body[0].exchengeRate;
        });

        return innerCost;
      }
    });
  </script>
</dom-module>

我有一个快速服务器 运行,信息正在正确传递,但 {{datagraph}} 标签保持为空。我想这可能是因为 post 请求是一个任意时间的任务,并且值是稍后传递的,但我也尝试使用 Promise 得到相同的结果。

有谁知道这样做的正确方法吗?

正如您所暗示的,getCost 总是 return 未定义,因为 return innerCost 将在 post 的回调之前执行。

Computed properties 旨在将其他属性作为参数并设计为同步。如果 getCost 接受了一些参数,即使那样你也会想要使用一个直接在回调中设置 this.datagraph 的观察者。

由于您没有向 getCost 提供任何参数,我建议您改用 ready callback 来发出 post 请求并在回调。

例如:

Polymer( {
    is: "cost-card",

    properties: {
        usr: { type: Number, value: 2 },
        command: { type: String, value: "SP_GetCostoCampania" },
        datagraph: Number
    },

    observers: [ "getCosto(command, usr)" ],

    getCosto: function ( command, usr ) {

        var options = {
            hostname: "localhost",
            path: "/",
            port: 8081,
            secure: false,
            method: "POST",
            headers: { "x-powered-by": "HTTPClient.js" },
            "Content-Type": "application/json"
        };

        const uri = `/executeGraph1?command=${command}&param1=${usr}`;
        new HTTPClient( options ).post( uri, ( err, res, body ) => {

            // values have changed, ignore result (ideally cancel the HTTP request)
            if ( command !== this.command || usr !== this.usr ) return;

            body = JSON.parse( body );

            this.datagraph = body[ 0 ].price * body[ 0 ].exchengeRate;

        } );

    }

} );