从Observable到BehaviorSubject

时间:2019-12-06 12:56:07

标签: angular rxjs angular8 angular-observable

我有并且可以观察到并且有条件:

let data$: Observable<DataModel[]>;

this.httpClient.get<DataModel[]>>(`data`)
   .pipe(map((result: DataModel[]>) => this.data$ = result));

let result: boolean = this.data$.pipe(
  map(x => x.find(y => y.child.some(z => z.id == id))),
  map(x => x ? ['B'].some(y => y === x.child.find(z => z.id == 2)) : false));

我现在将data$Observable<DataModel[]>更改为BehaviorSubject<DataModel[]>,并使用this.data$.next(result)来设置data$的值。

let data$: BehaviorSubject<DataModel[]>;

this.httpClient.get<DataModel[]>>(`data`)
   .pipe(map((result: DataModel[]>) => this.data$.next(result));

let result: boolean = this.data$.pipe(
  map(x => x.find(y => y.child.some(z => z.id == id))),
  map(x => x ? ['B'].some(y => y === x.child.find(z => z.id == 2)) : false));

使用BehaviorSubject时,我在this.data$.pipe(上收到错误消息

 undefined is not an object (evaluating 'this.data$.pipe')

我想念什么?

2 个答案:

答案 0 :(得分:1)

您应该初始化BehaviorSubject

let data$ = new BehaviorSubject<DataModel[]>(INITIAL_VALUE or undefined);

答案 1 :(得分:0)

我认为您错过了构造函数部分。

let data$: BehaviorSubject<DataModel[]> = new BehaviorSubject<DataModel[]>([]);

看看:Component interaction on angular.io

与行为主体和主题的唯一区别是,行为主体具有初始值并持有对最新值的引用,因此您可以订阅它并始终获得一个值。另一方面,主题只与时间有关。