首页 > 解决方案 > Angular中的嵌套订阅-性能问题?

问题描述

我有一个subscription存储和基于来自商店的价值,调用一个服务,我subscribe会进一步。

嵌套订阅会导致性能问题吗?虽已毁onDestroysubscription

ngOnInit() {
  this.currentYear = (new Date).getFullYear();
  this.statesubscription = this.contentServerStore
    .pipe(select(getContentServerState))
    .subscribe(val => {
      if (!this.checkValuesService.isNullOrUndefined(val) &&
        val.region.toUpperCase() == Constants.region.us
      ) {
        let contentRequest = new ContentRequest();
        this.regionService.getRegion(contentRequest).subscribe(region => {
          if (!this.checkValuesService.isNullOrUndefined(region)) {
            this.regionContent = <string>this.domSanitizer
              .bypassSecurityTrustHtml(region[Constants.regionKey]);
          }
        });
      }
    });
}

标签: angularsubscription

解决方案


尝试使用 flatMap 操作符来嵌套订阅。

ngOnInit() {
    this.currentYear = (new Date).getFullYear();
    this.statesubscription = this.regionService.getRegion(contentRequest).flatMap(region => this.contentServiceFunc(region)).subscribe()
}

private contentServiceFunc(region) {
    return this.contentServerStore.pipe(select(getContentServerState))
        .subscribe(val => {
            if (!this.checkValuesService.isNullOrUndefined(val) &&
                val.region.toUpperCase() == Constants.region.us
            ) {
                let contentRequest = new ContentRequest();

                if (!this.checkValuesService.isNullOrUndefined(region)) {
                    this.regionContent = < string > this.domSanitizer.bypassSecurityTrustHtml(region[Constants.regionKey]);
                }
            }

        });
}

推荐阅读