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

[Angular 2] Controlling Rx Subscriptions with Async Pipe and BehaviorSubjects的更多相关文章

  1. [Angular 2] Rendering an Observable with the Async Pipe

    Angular 2 templates use a special Async pipe to be able to render out Observables. This lesson cover ...

  2. [Angular] Bind async requests in your Angular template with the async pipe and the "as" keyword

    Angular allows us to conveniently use the async pipe to automatically register to RxJS observables a ...

  3. [Angular 2] Passing Observables into Components with Async Pipe

    The components inside of your container components can easily accept Observables. You simply define ...

  4. [Angular] Show a loading indicator in Angular using *ngIf/else, the as keyword and the async pipe

    The network may be unreliable and loading data may take time. Thus it is important to give the user ...

  5. [Angular 2] Controlling how Styles are Shared with View Encapsulation

    Style and View Encapsulation is best understood by seeing how each option (Emulated, Native, and Non ...

  6. [Angular 2] Using Array ...spread to enforce Pipe immutability

    Pipes need a new reference or else they will not update their output. In this lesson you will use th ...

  7. [Angular 2] Handle Reactive Async opreations in Service

    When you use ngrx/store and you want to fire a service request. When it sucessfully return the respo ...

  8. [Angular 2] Rendering an Observable Date with the Async and Date Pipes

    Instead of simply pushing numbers on a timer into the template, now we'll move on to pushing actual ...

  9. [Angular 2] Async Http

    Async Pipe: The Asynce pipe receive a Promise or Observable as  input and subscribes to the input, e ...

随机推荐

  1. asp.net mvc源码分析-Action篇 IModelBinder

    我们首先还是看看ReflectedParameterBindingInfo的Binder属性吧: public override IModelBinder Binder {            ge ...

  2. 拜托,这才是“Uber”的正确读法

    在美国,私家车主可以注册成为Uber司机,这对传统的出租车行业形成了很大的挑战,同时也让Uber始终处于舆论的风口浪尖. 7月14日,美国用车应用Uber正式宣布进入北京市场.在进入中国后,Uber选 ...

  3. html5 base64基础

    base64常见的编码形式,二进制文件.图片.视频等     如何弄出来一个base64?     a). FileReader         readAsDataURL();     b). 工具 ...

  4. 存量数据处理结果查询.txt

    请求报文:<?xml version="1.0" encoding="UTF-8"?><PDL><PDL-Head>< ...

  5. python scp

    scp 0.10.2 Downloads ↓ scp module for paramiko Pure python scp module====================== The scp. ...

  6. Swift-CALayer十则示例

    作者:Scott Gardner   译者:TurtleFromMars原文:CALayer in iOS with Swift: 10 Examples 如你所知,我们在iOS应用中看到的都是视图( ...

  7. ODBC 是什么

    In computing, ODBC (Open Database Connectivity) is a standard programming language middleware API fo ...

  8. How Tomcat Works(五)

    本文接下来介绍tomcat的默认连接器,Tomcat中的默认连接器必须满足以下要求: 实现org.apache.catalina.Connector接口 负责创建实现org.apache.catali ...

  9. android Notification和NotificationManager的使用

    Notification和NotificationManager 1.Broadcast Receiver组件没有提供可视化的界面来显示广播信息.这里我们可以使用Notification和Notifi ...

  10. non-manifold Mesh(非流形网格)

    三角网格曲面中,大多的算法基于流形网格manifold mesh,其定义如下: 1)Each edge is incident to only one or two faces: 一条网格边为一个或两 ...