繁体   English   中英

Angular rxjs:延迟订阅直到其他 Observable 发出

[英]Angular rxjs: Delay subscription till other Observable emits

我有 2 个订阅 - 一个是我的 ActivatedRoute 的订阅,另一个是来自 ngrx 商店的订阅。

  ngOnInit() {
    this.menuItems$ = this.store.select('menuItems');
    this.menuItems$.subscribe(data => {
      this.menuItems = data.menuItems;
    });
  }

  ngAfterViewInit() {
    this.fragmentSubscription = this.route.fragment.pipe(
      filter((fragment: string) => typeof fragment === 'string')
    ).subscribe((fragment: string) => {
      setTimeout(() => {
        const element: ElementRef = this.menuItems.find(menuItem => menuItem.link === fragment).element;
        if(element !== undefined) {
          element.nativeElement.scrollIntoView({ behavior: "smooth", block: "start", inline: "center" });
        }
      });
    });
  }

由于我的 ActivatedRoute(片段)订阅取决于我的商店订阅数据,我想延迟我的 ActivatedRoute(片段)订阅,直到我的商店第一次被订阅

是否有任何 rxjs 运营商为此?

肿瘤坏死因子

根据您的评论...

如果 Store 第一次发出已经完成,我不想再在 ActivatedRoute 订阅时等待它

您正在寻找combineLatest ,其中...

当任何 observable 发出一个值时,从每个发出最后一个发出的值。

所以我建议如下:

import { Subscription, combineLatest } from 'rxjs';

// ...

mySubscription: Subscription;

ngOnInit() {
  this.mySubscription = combineLatest(
    this.store.select('menuItems'),
    this.route.fragment.pipe(
      filter((fragment: string) => typeof fragment === 'string')
    )
  // DON'T USE ANY, type your data...!
  ).subscribe((data: [any, any]) => {
    this.menuItems = data[0];
    const fragment = data[1]
    // do your thing...
  })
}

ngOnDestroy() {
  this.mySubscription.unsubscribe();
}

如果可能,不要从存储中获取 init 中的数据。 从解析器中获取它们。

您当然可以从解析器的商店中获取它们,然后在 init function 中将它们作为值访问。

在此处查找更多信息https://angular.io/api/router/Resolve

暂无
暂无

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

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