gpt4 book ai didi

javascript - Polymer 计算属性上的空值

转载 作者:行者123 更新时间:2023-12-03 03:31:02 25 4
gpt4 key购买 nike

我尝试在 Polymer 中使用计算属性,但总是得到一个空值。在本例中,我的自定义元素中有一个名为 datagraph 的属性。我向服务器发出 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>

我有一个正在运行的 Express 服务器,信息正在正确传递,但 {{datagraph}} 标记保持为空。我认为这可能是因为 post 请求是一个异步任务,并且值是稍后交付的,但我也尝试过使用 Promise 得到相同的结果。

有谁知道正确的方法吗?

最佳答案

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

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

由于您没有向 getCost 提供任何参数,因此我建议您使用 ready callback发出 post 请求并在回调中设置 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;

} );

}

} );

关于javascript - Polymer 计算属性上的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46101853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com