preface

RXJS is undeniably powerful and convenient when using Angular, but its various operators can be a real pain in the neck when you first learn it. Use and find the various operators to record, easy to find.

Filter operator

  • StartWith: Adds the element to be sent at the beginning
  • Filter: Pass function to filter sent elements (similar to array filter)
  • Scan: pass function (similar to data reduce function, the first argument is the return value, the second value is the data stream)
  • Skip: Pass in a number and skip N elements
  • SkipUntil receives an Observable, ignoring the value before the Observable is emitted.
  • SkipWhile accepts function, returns true and is filtered, false and unfiltered.
  • Last: take the last element (note where it is placed)
  • First: take the last element (notice where it is placed)
  • Take: Pass in a number and take only N elements
  • TakeUntil receives an Observable, which completes when it emits a value
  • TakeWhile receives function and completes once it returns false
import { from, timer, Subject } from 'rxjs';
import { filter, take, last, startWith, skip } from 'rxjs/operators';
destroy$ = new Subject();
ngOnInit// emit (1, 2, 3, 4, 5) constsource= from([1, 2, 3, 4, 5]); Const example = source.pipe(// startWith 6, 8, 1, 2, 3, 4, 5) (num => num % 2 === = 0); // Scan ((all,item) => all + item); // take(2); TakeWhile (x => x < 3), take example (x => x < 3), TakeUntil (timer(5000)), takeUntil(this.destroy$), which is usually used when component destruction is complate); example.subscribe(val => { console.log(`The number:${val}`)}); }ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complate();
}
Copy the code

If the throttle

  • Debounce buffering will root out an output value that is less than the specified time between outputs.
  • DebounceTime: number of milliseconds to receive, discarding emitted values that are less than the specified time between outputs (starting after the last input of milliseconds).
  • ThrottleTime: the number of milliseconds after which the latest value will be sent.
Debounce (val => timer(val * 200)),); // Debounce (val => timer(val * 200)). fromEvent(this.input.nativeElement,'input'DebounceTime (1000) debounceTime(1000) returns the latest value if the last input is less than 2 seconds. The last input will not be triggered if the last input is less than 2 seconds. throttleTime(2000) ).subscribe( (x: any) => { console.log('x', x.target.value);
});
Copy the code

subsequent

That’s all for now, and then there’s the merge operator and so on, so take your time. Forgot to turn it over again!