typescript 将switchMap()与嵌套订阅调用进行比较。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript 将switchMap()与嵌套订阅调用进行比较。相关的知识,希望对你有一定的参考价值。

import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {ContactsService} from '../contacts.service';
import {Contact} from '../models/contact';

import 'rxjs/add/operator/switchMap';
import {Subscription} from 'rxjs';

@Component({
  selector: 'trm-contacts-detail',
  templateUrl: './contacts-detail.component.html',
  styleUrls: ['./contacts-detail.component.css']
})
export class ContactsDetailComponent implements OnInit {
  subscription: Subscription;

  contact: Contact;

  constructor(private contactsService: ContactsService, private route: ActivatedRoute) {
  }

  /**
   *  BEST WAY!
   *  We need to subscribe to params changes because this component is
   *  reused when jumping between contacts. Hence ngOnInit isn't called
   */
  ngOnInit() {
    this.subscription = this.route.params
        .switchMap(params => this.contactsService.getContact(params['id']))
        .subscribe(contact => this.contact = contact);
  }

  /**
   * BAD WAY!
   * This is the traditional nested approach to chaining async stream events.
   * Notice the `clean()` function required to unsubscribe on errors and completion.
   */
  ngOnInit2() {
    this.subscription  = this.route.params.subscribe(params => {
      let clean = () => restSub.unsubscribe();
      let restSub = this.contactsService
                        .getContact(params['id'])
                        .subscribe(contact => {
                          this.contact = contact;
                          clean();
                        }, clean );
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

}

以上是关于typescript 将switchMap()与嵌套订阅调用进行比较。的主要内容,如果未能解决你的问题,请参考以下文章

如何以及在何处使用 Transformations.switchMap?

在Angular App中的Obseable POST请求中使用switchMap

switchMap 中 of(...) 和 [...] 的区别

map() 和 switchMap() 方法有啥区别?

了解rxjs中的SwitchMap

为什么retryWhen在switchMap中不起作用(Ngrx Effects rxjs)