我有一个服务,它从服务器获取一些数据并更新一些主题,在我组件的 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();
        }
    });
  }

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

最佳答案

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

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

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

关于angular - 订阅第一次不工作的主题 oninit,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56038063/

10-16 19:48