订阅一个在首次使用时不工作的主题

时间:2019-05-08 09:59:10

标签: angular rxjs observable angular2-observables

我有一项服务,该服务从服务器获取一些数据并更新某些主题,并且我正在该组件的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);

      });
  }

我正在组件中订阅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();
        }
    });
  }

,但是当我从另一个组件导航到该组件时,它没有得到主题的响应。但是,从该组件导航到同一组件后,它可以正确获得响应。有人可以帮助我了解这里发生了什么吗?

1 个答案:

答案 0 :(得分:2)

您在请求数据后订阅了主题。

您必须先订阅,然后再请求数据。

ngOnInit() {
    this.dashboardDataService.documentsData.subscribe(...);
    this.dashboardDataService.getInboxData(); 
}