why should we use subscribe() over map() in Angular?

前端 未结 5 1500
花落未央
花落未央 2020-12-07 22:28

I am trying to take advantage of observables in angular2 and got confused on why should i use map() over subscribe(). Suppose i am getting values f

5条回答
  •  一向
    一向 (楼主)
    2020-12-07 22:47

    Observables are streams and they are designed to be written in functional streams. You should use RxJS operations because it is the 'functional' way of implementing subsctiptions to observables. Usually this happens when we take data outside of the Observable stream.

    This is an asynchronous operation forced to work synchronously.

    bad_example() {
      let id;
      this.obs.subscribe(param => id = param['id']);
        this.get(id).subscribe(elem => this.elem = elem);
    }
    

    This is an asynchronous operation that works as supposed to work. (As a stream)

    good_example() {
      this.obs
        .map(param => param['id'])
        .switchMap(id => return this.get(id))
        .subscribe(elem => this.elem = elem);
    }
    

提交回复
热议问题