Reputation: 49
i try to store data from api in prometheus into global variable, i successfully store it from api into variable in vue js using axios, i tried to execute .then(console.log(this.infoCpu) and it worked in console, it has different value because it's from real time situation, but if i try to declare it with global variable on body html it does not work, the value if i try to console as global variable it will has null value, is it the null value comes from the value that i setup from the code on vue js? then how i store from data api into global variable that can be show if i try to show it, example code document.write("variable-that-contain-data-from-api") i need the variable because i use some library called gauge that need varibable contain data cpu real time from api
it is the code
var newCpu = new Vue({
el: '#cpuHead',
data () {
return {
infoCpu: null
}
},
mounted () {
axios
.get('http://172.168.20.21:9090/api/v1/query?query=prometheus_tsdb_head_series_created_total')
.then(response => (this.infoCpu = response.data.data.result[0].value[1]))
.then(console.log(this.infoCpu))
}
})
that was the code that use to get data from api, and in console that is the right value of the variable this.infoCpu comes up at console.
but when i tried to show it at html body using document.write(newCpu.infoCpu), it does not has value, that just showing null default value that i set up on vue js code
but i try to show it using this code, it comes up
<div id="cpuHead>
{{ infoCpu }}
</div>
so how to correctly save data from api into variable and use it into another library that i want to use, because it looks like does not mount data from api if try to show it with document.write(newCpu.infoCpu), i need the varibale to work with my gauge library that need a variable
Upvotes: 1
Views: 765
Reputation: 23500
Try to wait for response :
const newCpu = new Vue({
el: '#cpuHead',
data () {
return {
infoCpu: null
}
},
async mounted () {
await axios
.get('http://172.168.20.21:9090/api/v1/query?query=prometheus_tsdb_head_series_created_total')
.then(response => {
this.infoCpu = response.data.data.result[0].value[1]
console.log(this.infoCpu)
})
.catch((error) => {
this.infoCpu = error.message
console.log(error)
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.25.0/axios.min.js" integrity="sha512-/Q6t3CASm04EliI1QyIDAA/nDo9R8FQ/BULoUFyN4n/BDdyIxeH7u++Z+eobdmr11gG5D/6nPFyDlnisDwhpYA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="cpuHead">
<div v-if="!infoCpu">loading ...</div>
{{ infoCpu }}
</div>
Upvotes: 1