简体   繁体   English

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

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

I have 2 Subscription - one is a subscription of my ActivatedRoute and another from ngrx Store.我有 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" });
        }
      });
    });
  }

As my ActivatedRoute (fragment) subscription depends on my store subscription data, I want to delay my ActivatedRoute (fragment) subscription till my Store is subscribed for the first time由于我的 ActivatedRoute(片段)订阅取决于我的商店订阅数据,我想延迟我的 ActivatedRoute(片段)订阅,直到我的商店第一次被订阅

Is there any rxjs operator for this?是否有任何 rxjs 运营商为此?

Tnx肿瘤坏死因子

Based on your comment...根据您的评论...

If the first time when the Store emits has completed, I no longer want to wait for it when the ActivatedRoute subscribes如果 Store 第一次发出已经完成,我不想再在 ActivatedRoute 订阅时等待它

You are looking for combineLatest , which...您正在寻找combineLatest ,其中...

When any observable emits a value, emit the last emitted value from each.当任何 observable 发出一个值时,从每个发出最后一个发出的值。

So I suggest the following:所以我建议如下:

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();
}

Don't get your data in init from the store if possible.如果可能,不要从存储中获取 init 中的数据。 Get them from a resolver.从解析器中获取它们。

You can ofcourse get them from the store in the resolver and then access them in the init function as a value.您当然可以从解析器的商店中获取它们,然后在 init function 中将它们作为值访问。

Look for more information here https://angular.io/api/router/Resolve在此处查找更多信息https://angular.io/api/router/Resolve

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

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