zoukankan      html  css  js  c++  java
  • [Angular 2] Controlling Rx Subscriptions with Async Pipe and BehaviorSubjects

    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

  • 相关阅读:
    41.用c++编写程序:从键盘上任意输20个1-99之间的整数,分别统计其个位数0-9的数字各有多少
    【编程规范整理】
    CI/CD----jenkins+gitlab+django(内网)
    tomcat访问日志
    Django + celery +redis使用
    CI/CD----jenkins安装配置
    linux 批量删除进程
    django数据查询之聚合查询和分组查询
    django middleware介绍
    git初始化命令行指引
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5926784.html
Copyright © 2011-2022 走看看