[英]how to pass a response from the service to the controller Angularjs?
我在服務中有一個要求:
getCommentText(id: number) {
var data = null
this.$http.post(this.path + '/' + id + '/GetComment', data, {
headers: { "Content-Type": "application/json" }
}).then(r => r.data);
}
和控制器
openComment($event) {
this.commentid = $event.target.id;
this.service.getCommentText(this.commentid);
}
我需要將響應從服務傳遞回控制器。 最終將得到什么: var text =(響應)我試圖在控制器中使用訂閱。 但這對我不起作用。 這是第一位Angulyar,我不太了解他。 我該怎么辦?
您的服務應返回承諾:
getCommentText(id: number) { var data = null return this.$http.post(this.path + '/' + id + '/GetComment', data, { headers: { "Content-Type": "application/json" } }).then(r => r.data); } openComment($event) { this.commentid = $event.target.id; this.service.getCommentText(this.commentid).then(response => { console.log(response); }); }
$http.post
返回一個Promise
。 Promise
是一個表示值或錯誤的對象,兩者都會在將來的某個時刻發生。 由於這是一個對象,因此可以將其返回,如下所示:
getCommentText(id: number) {
return this.$http.post(this.path + '/' + id + '/GetComment', data, {
headers: {
'Content-Type': 'application/json'
}
}).then(r => r.data);
}
然后可以在您的控制器中使用它:
openComment($event) {
this.commentid = $event.target.id
this.service.getCommentText(this.commentid)
.then((text) => {
this.commentText = text
})
由於getCommentText
可能會失敗,因此您應該小心處理失敗情況。 另外,由於這是異步的,因此請考慮向用戶顯示某種加載指示符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.