【问题标题】:subscribing to a subject not working for first time oninit订阅第一次 oninit 不起作用的主题
【发布时间】:2019-05-08 09:59:10
【问题描述】:

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

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

【问题讨论】:

标签: angular rxjs observable angular2-observables


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 1970-01-01
    • 2023-03-22
    • 2020-08-16
    • 2020-12-13
    • 2017-01-19
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多