简体   繁体   中英

takeUntil does not work with BehaviorSubject

I have the following BehaviorSubject defined:

  private posts = new BehaviorSubject<any[]>([]);

and on init:

ngOnInit() {
  this.posts
    .takeUntil(!this._postsLoaded)
    .subscribe(x => {
       this._postsLoaded = true;
        // do something
    });
}

But it gets the following error, although it should work:

Property 'takeUntil' does not exist on type 'BehaviorSubject<any>'

If you want to use like a chain syntax , You have to install rxjs compat also for backward comptability.

npm install --save rxjs-compat

But I would suggest use pipes

import { takeUntil } from 'rxjs/operators';
ngOnInit() {
  this.posts.pipe(
    takeUntil(!this._postsLoaded)
    ).subscribe(x => {
       this._postsLoaded = true;
        // do something
    };
}

Sample Stackblitz

https://stackblitz.com/edit/rxjs-takeuntilexample?file=index.ts

There're two things:

  1. In RxJS 6 you should use pipable operators. If you have to use the old "patch" style of operators you'll need to include rxjs-compat package

  2. The takeUntil() operator takes as a parameter another Observable so what you have now will throw an error anyway.

    Maybe you should use takeWhile() instead. See this answer ( RxJS takeWhile but include the last value ) if you want to also include the last value that completed the chain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM