简体   繁体   中英

Create filtered Subject to Observable in Angular

Hi I have a private Subject that I do not want to expose, so I am creating different Observable s from the single Subject :

public numberChange$: Observable<number>;
public oddChange$: Observable<number>;
public evenChange$: Observable<number>;
private number: Subject<number>;
constructor() {
  this.number = new Subject<number>();
  this.numberChange$ = this.number.asObservable();
  this.oddChange$ = this.number.filter(n => n % 2 === 1).asObservable();
  this.evenChange$ = this.number.filter(n => n % 2 === 0).asObservable();
}

So that others can subscribe to numberChange$ if they want to know when the number has changed. If they want to know ONLY when the change is an odd number, they can subscribe to oddChange$ . Same goes for evenChange$ .

The code above does not work because after this.number.filter() I cannot call asObservable() anymore. How do you fix the code above to achieve what I have described?

An Observable is returned from Observable.filter . So there isn't a need to call asObservable() , just subscribe to the returned value.

this.number = new Subject<number>();
this.numberChange$ = this.number.asObservable();
this.oddChange$ = this.number.filter(n => n % 2 === 1);
this.evenChange$ = this.number.filter(n => n % 2 === 0);
this.oddChange$.subscribe((x) => { console.log(x) } );

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