Sho*_*bal 4 observable rxjs angular2-observables angular
我有一项服务从服务器获取一些数据并更新一些主题,在我的组件的 ngOnInit 函数中我正在订阅该主题。我已确认主题已正确更新。
以下是我的服务功能,它从服务器获取数据并更新主题。
getInboxData(id?) {
this.inboxID = id;
this.loadingData.next( // tells to start showing loading animation
{
showloading: true,
clearDocuments: this.shouldClearDocuments()
});
this.getInboxCount();
this.dashboardService.getInbox(id, this.page)
.subscribe((response) => {
for (const inbox of response['results']) {
this.documents.push(inbox.document);
// tells to stop showing loading animation
this.loadingData.next({showloading: false, clearDocuments: this.shouldClearDocuments()});
}
if (response.next != null) {
this.page++;
// this.getInboxData(id);
}else {
this.page = 1; // reset
}
this.documentsData.next(response);
});
}
Run Code Online (Sandbox Code Playgroud)
我正在我的组件中订阅documentsData。以下是组件的代码。
ngOnInit() {
this.dashboardDataService.getInboxData();
this.dashboardDataService.documentsData
.subscribe((response) => {
this.isLoadingMoreResult = false;
this.loading = false;
for (const entry of Object.values(response.results)){ // save new entries
this.documents.push(entry);
}
this.documentsLoaded = Promise.resolve(true);
this.filteredDocuments = this.documents; // both should be same when user gets new data
console.log(this.filteredDocuments);
$('#documentContentSearch').val(''); // reset text in searchBar
// if (this.documents.length >= 8) { // if list is more than 8 then show scroll
$('#tableContainer').css({'height': $('#mySideBar').innerHeight() - 195});
const $myThis = this;
$('#tableContainer').scroll(function(){
if (!$myThis.isLoadingMoreResult) { // if it is not already loading result
$myThis.loadMoreResults();
}
});
$('#dropdown').scroll(function(){
if (!$myThis.isLoadingMoreResult) { // if it is not already loading result
$myThis.loadMoreResults();
}
});
// load two results in first time
if (this.dashboardDataService.page === 2) {
this.loadMoreResults();
}
});
}
Run Code Online (Sandbox Code Playgroud)
但当我从另一个组件导航到该组件时,它没有得到主体的响应。但是,从该组件重新导航到同一组件后,它会得到正确的响应。有人可以帮助我了解这里发生了什么吗?
您在请求数据后订阅该主题。
您必须订阅然后请求数据。
ngOnInit() {
this.dashboardDataService.documentsData.subscribe(...);
this.dashboardDataService.getInboxData();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5874 次 |
| 最近记录: |