如何在Observer中检测取消订阅

时间:2018-04-27 08:08:10

标签: observable angular5 rxjs5

我将一个http调用包装到一个新的Observable,但我无法检测订阅是否被取消:

constructor( @Inject(Http) private http: Http) {
}


...


const observable = Observable.create((observer: Observer<any>) => {
            this.http.post(url, body)
                .subscribe((p) => {
                    observer.next(p.json());
                    observer.complete();
                }, (err) => {
                    observer.error(err);
                    observer.complete();
                });
        });
const subscription = observable.subscribe((r) => { alert("result : "+r); }, (err) => { alert("error occured");}

subscription.unsubscribe(); // if user cancels the request

如果用户取消订阅,我如何在Observable.create(...)中检测到?当外部Observable被取消时,我想取消http post请求。

1 个答案:

答案 0 :(得分:2)

您可以手动创建unsubscribe功能,如:

 constructor(public http: HttpClient) {
    let url = 'google.kz';

    const observable = Observable.create((observer: Observer<any>) => {
      let cancel: Subscription = this.http.post(url, {})
        .subscribe((p) => {
          observer.next(p);
          observer.complete();
        }, (err) => {
          observer.error(err);
          observer.complete();
        });

      // Provide a way of canceling and disposing the internal observables
      return function unsubscribe() {
        cancel.unsubscribe();
      };
    });

    let unsc = observable.subscribe(data => {
      console.log(data);
    })
    console.log('unsubscribe', unsc);

    unsc.unsubscribe();
  }

所以,当你调用外部observable的unsubscribe()函数时,内部observables取消订阅也取决于它是如何实现的

StackBlitz Demo