【问题标题】:Angular rxjs: Delay subscription till other Observable emitsAngular rxjs:延迟订阅直到其他 Observable 发出
【发布时间】:2019-10-30 16:13:00
【问题描述】:

我有 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 操作符吗?

Tnx

【问题讨论】:

  • @penleychan 看起来不错,但我只想这样做一次,而不是总是这样做。如果Store第一次发出已经完成,我不想再等ActivatedRoute订阅了
  • 通过 router.navigate 方法中的 navigationExtras 更好地传递 menueItems 列表,从您导航到此页面的位置

标签: javascript angular typescript rxjs


【解决方案1】:

根据您的评论...

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

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

当任何 observable 发出一个值时,发出每个 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();
}

【讨论】:

  • 完美运行,完全符合我的需求。谢谢。
  • 非常欢迎您,很高兴听到它适合您! :)
【解决方案2】:

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

您当然可以从解析器中的存储中获取它们,然后在 init 函数中将它们作为值访问。

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

【讨论】:

  • 很好的方法,但这在这种情况下不起作用,因为我在 ngOnInit 之后从子组件中检索 Store 的数据(因为它们仅在父组件被激活后加载)。不过谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-03
  • 2018-01-17
  • 1970-01-01
  • 2018-04-03
  • 1970-01-01
相关资源
最近更新 更多