繁体   English   中英

如何在 Angular 中使 function 成为 Observable

[英]How to make a function an Observable in Angular

我的 IONIC 应用程序中有以下代码,它设置了一些过滤器。 第一次运行时,过滤器始终未定义,因为查询在完成设置之前执行。 我的代码所做的是它从离子存储中获取当前过滤器 object,更新存储,然后获取新更新的过滤器并对 api 执行 http 请求。

setFilter(params: any) {
    console.log('calling Set Filter');
    // tslint:disable: max-line-length
    this.storage.get('filter').then(filterStored => {
      console.log('Filter ', filterStored);

      if (params.type === 'privacy') {
      this.storage.set('filter', { privacy: params.option.name, occupancy: filterStored.occupancy, status: filterStored.status } ).then(res => {});
    }
      if (params.type === 'occupancy') {
      this.storage.set('filter', { occupancy: params.option.name, privacy: filterStored.privacy, status: filterStored.status  } ).then(res => {});
    }

      if (params.type === 'status') {
      this.storage.set('filter', { status: params.option.name, privacy: filterStored.privacy, occupancy: filterStored.occupancy } ).then(res => {});
    }

  this.storage.get('filter').then(refreshfilterStored => {
  console.log('Updated Filter ', refreshfilterStored);
  this.queryFilter =  refreshfilterStored;
 });
});

this.farmStreetHouses$ = this.farmStreetHouseProvider.getFilteredPrivacy(this.farm.guid, this.street.sasn, this.queryFilter)
    .pipe(
      tap((res): any => {
        this.farmStreetHousesCache = res;
      }),
    );
}

所以我想要实现的是,在我们调用farmStreetHouses Observable之前,我们完成所有获取原始存储、更新存储、更新存储的事情

如果您只是将您的 Observable 从您的过滤器获取中移动到then() function 中,您应该为您的请求设置正确的过滤器:


setFilter(params: any) {
  console.log('calling Set Filter');
  // tslint:disable: max-line-length
  this.storage.get('filter').then(filterStored => {
    console.log('Filter ', filterStored);

    if (params.type === 'privacy') {
      this.storage.set('filter', { privacy: params.option.name, occupancy: filterStored.occupancy, status: filterStored.status } ).then(res => {});
    }
    else if (params.type === 'occupancy') {
      this.storage.set('filter', { occupancy: params.option.name, privacy: filterStored.privacy, status: filterStored.status  } ).then(res => {});
    }
    else if (params.type === 'status') {
      this.storage.set('filter', { status: params.option.name, privacy: filterStored.privacy, occupancy: filterStored.occupancy } ).then(res => {});
    }

    this.storage.get('filter').then(refreshfilterStored => {
      console.log('Updated Filter ', refreshfilterStored);
      this.queryFilter = refreshfilterStored;

      this.farmStreetHouses$ = this.farmStreetHouseProvider.getFilteredPrivacy(this.farm.guid, this.street.sasn, this.queryFilter)
        .pipe(tap((res): any => {
          this.farmStreetHousesCache = res;
        }));
    }
  });
});

(我认为如果你修复缩进并使用else子句,就像我在这里一样,代码会更容易阅读。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM