如何获取RxJS subscribe()函数中的变量?
问题描述:
我正在使用angular2。 现在,我很难在subscribe()中获得一个值。 我知道它会返回null。 如何返回正确的值?如何获取RxJS subscribe()函数中的变量?
这里是我的代码。任何人都会给我建议,这会非常有帮助。谢谢:)
this.deliveryService.deliveryCancel(rowInfo.branchId, rowInfo.id).subscribe(
res => {
var data = res.json();
this.getDeliveryList();
this.msgs.push({ severity: 'success', summary: 'Info', detail: rowInfo.deliveryStatus });
},
err => {
this.errMessage = <any>err;
this.msgs.push({ severity: 'error', summary: 'Error', detail: this.errMessage });
}
);
console.log(data);
deliveryCancel()
deliveryCancel(branchId, deliveryId) {
const headers = new Headers({
'Content-Type': 'application/json'
});
return this.http.put(this.testUrl + '/admin/branches/' + branchId + '/deliveries/' + deliveryId + '/cancel', {
headers: headers
})
.catch(handleError);
}
答
您不能访问res.json()这样的。并将“数据”初始化为类变量。尝试这个。
data = {};
this.deliveryService.deliveryCancel(rowInfo.branchId, rowInfo.id).subscribe(
res => {
this.data = res['_body'];
this.getDeliveryList();
this.msgs.push({ severity: 'success', summary: 'Info', detail: rowInfo.deliveryStatus });
},
err => {
this.errMessage = <any>err;
this.msgs.push({ severity: 'error', summary: 'Error', detail: this.errMessage });
}
);
console.log(data);
答
这不是一个有问题的问题,而是一个关于异步行为打破执行流程的javascript问题。
Suscribing意味着在deliveryCancel()返回的任何错误或成功时,将调用res函数或err函数。
您的console.log(数据)只能执行一次,并且绝不是这些功能的一部分。
这是你所追求的:
this.deliveryService.deliveryCancel(rowInfo.branchId, rowInfo.id).subscribe(
res => {
this.data = res['_body'];
this.getDeliveryList();
this.msgs.push({ severity: 'success', summary: 'Info', detail: rowInfo.deliveryStatus });
console.log(data);
},
err => {
this.errMessage = <any>err;
this.msgs.push({ severity: 'error', summary: 'Error', detail: this.errMessage });
console.log(data);
}
);
你能澄清你的问题,它涉及到你的代码发布? – shusson
RXJS和你的问题中的订阅方法在哪里? –
@shusson,我只是编辑我的代码。我的坏:( –