我正在尝试从服务中获取价值。我需要将此值发送给其他服务。代码是这样的:
datameterId: string;
ngOnInit() {
this.graphCtrl.getMeter(this.id).subscribe(
response => {
this.ultimoValor = response["body"]["ultimoDatoConocido"];
this.ultimoValorCierre = response["body"]["ultimoDatoCierreMes"];
this.consumoMediaDiaria = response["body"]["consumoMedioDiario"];
this.consumoMediaMensual = response["body"]["consumoMedioMensual"];
this.consumoUltimoMes = response["body"]["consumoUltimoMes"];
this.alertas = response["body"]["alarmasActivas"];
this.contador = response["body"]["resumenDatameter"]["contador"];
this.datameterId = response["body"]["resumenDatameter"]["id"];
},
error => {
console.log(error);
}
);
this.config();
}
config() {
console.log(this.datameterId); //NULL
}
问题:当我调用另一个函数时,值丢失了,所以我无法使用它。代码有什么问题?
更新
如果我把this.config();在响应中返回
Cannot read property 'every' of undefined
at DaterangepickerComponent.push..
更新2
如果我删除
this.ranges = {
Hoy: [moment(), moment()],
Ayer: [moment().subtract(1, "days"), moment().subtract(1, "days")],
"Últimos 7 días": [moment().subtract(6, "days"), moment()],
"Últimos 30 días": [moment().subtract(29, "days"), moment()],
"Este mes": [moment().startOf("month"), moment().endOf("month")],
"Mes pasado": [
moment()
.subtract(1, "month")
.startOf("month"),
moment()
.subtract(1, "month")
.endOf("month")
]
};
不显示错误,但不起作用。数据范围需要工作的范围。
答案 0 :(得分:1)
这是错误的,因为您调用函数而不必等待值。您需要在订阅内调用函数或使用async / await
this.graphCtrl.getMeter(this.id).subscribe(res =>{
\\Do your stuff
this.config();
})
答案 1 :(得分:0)
订阅后致电
ngOnInit() {
this.graphCtrl.getMeter(this.id).subscribe(
response => {
this.ultimoValor = response["body"]["ultimoDatoConocido"];
this.ultimoValorCierre = response["body"]["ultimoDatoCierreMes"];
this.consumoMediaDiaria = response["body"]["consumoMedioDiario"];
this.consumoMediaMensual = response["body"]["consumoMedioMensual"];
this.consumoUltimoMes = response["body"]["consumoUltimoMes"];
this.alertas = response["body"]["alarmasActivas"];
this.contador = response["body"]["resumenDatameter"]["contador"];
this.datameterId = response["body"]["resumenDatameter"]["id"];
this.config();<***************
},
error => {
console.log(error);
}
);
}