Polymer计算的属性上的空值

时间:2017-09-07 17:10:11

标签: javascript asynchronous polymer

我正在尝试在Polymer中使用计算属性,但我总是得到一个空值。在这种情况下,我的自定义元素中有一个名为datagraph的属性。我向服务器发出一个帖子请求,获取一个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并获得相同的结果。

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

1 个答案:

答案 0 :(得分:1)

正如您所暗示的那样,getCost总是会返回undefined,因为return innerCost将在帖子的回调之前执行。

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

由于您没有向getCost提供任何参数,我建议您改为使用ready callback发出请求并在回调中设置this.datagraph

例如:

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;

        } );

    }

} );