[Angular 2] Controlling Rx Subscriptions with Async Pipe and BehaviorSubjects

本文介绍如何通过BehaviorSubject优化Angular应用中HTTP请求的订阅问题,避免因多次使用AsyncPipe而导致不必要的网络请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Each time you use the Async Pipe, you create a new subscription to the stream in the template. This can cause undesired behavior especially when network requests are involved. This lesson shows how to use a BehaviorSubject to observe the http stream so that only one request is made even though we still have two Async pipes in the template.

 

hero.component.html:

<div>
  <h2>{{description}}: {{(hero | async)?.name}}</h2>
  <div>
    <a [routerLink]="['/heros', prev()]">Previous</a>
    <a [routerLink]="['/heros', next()]">Next</a>
  </div>
  <div>
    <input type="text" #inpRef (keyup.enter)="saveHero(inpRef.value)">
  </div>
  <br>
  <img src="{{(hero | async)?.image}}" alt="">
  <div>
    <a [routerLink]="['/heros']">Back</a>
  </div>
</div>

Here you can see, we use twice 'async' pipe, it means we subscribe the stream twice:

    this.hero = this.route.params
     .map((p:any) => {
      this.editing = false;
      this.heroId = p.id;
      return p.id;
     })
     .switchMap( id => this.starwarService.getPersonDetail(id));

In network tab, we can see it calls '1' api twice.

 

To solve this problem, we can use 'BehaviorSubject' :

    this.hero = new BehaviorSubject({name: 'Loading...', image: ''})

    this.route.params
     .map((p:any) => {
      this.editing = false;
      this.heroId = p.id;
      return p.id;
     })
     .switchMap( id => this.starwarService.getPersonDetail(id))
    .subscribe( this.hero);

This can solve problem, because we only have one subscription to the stream with HTTP get in it.

We do have two subscriptions to this contact here and here because a behavior subject is still an observable but it's not going to make two requests because now it's just observing what comes from the stream instead of basically invoking it twice. Because now we have one subscription to the stream with HTTP calling it being observed by something with two subscriptions on it.

See more: http://www.cnblogs.com/Answer1215/p/5784167.html

 

Github

转载于:https://www.cnblogs.com/Answer1215/p/5926784.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值