如何将主题值传递到管道内的switchMap?

时间:2019-09-02 10:32:53

标签: rxjs

我的行为主体状态低于标准,并且已存储为studentNo来自其他组件的值,

const initialState: any = {
   studentNo: '',
}
private _state$: BehaviorSubject<any> = new BehaviorSubject<any>(initialState);
get state$(): Observable<any> { return this._state$; }

private _requestStudent$: Subject<void> = new Subject<void>();

然后我在服务文件构造器块中监听this.requestStudent$主题,

constructor(): void {
   this._requestStudent$.pipe(
      tap(this.state$),//Is this correct way to pass state$ value to below switchMap?,
      switchMap(this.requestStudentDetail.bind(this)),
   ).subscribe(this._studentList$);
}

requestStudentDetail(state: any): Observable<any> {
   return this.http....// I got the undefined value, If i print state.studentNo value here
}

public getStundentDetail(): void {// i called this function from component A
   this._requestStudent$.next();
}

如何在没有订阅this.state$的情况下将状态值(studentNo)传递给http api服务功能。

2 个答案:

答案 0 :(得分:1)

好吧,您可能想先switchMap声明状态?

this._requestStudent$.pipe(
  switchMap(this.state$),
  switchMap((studentNumber) => this.requestStudentDetail(studentNumber)),
).subscribe(this._studentList$);

答案 1 :(得分:0)

我们可以使用'withLatestFrom'rxjs运算符从主题中获取值,因此我可以重新编写如下代码,

this._requestStudent$.pipe(
  withLatestFrom(this.state$),
  switchMap(this.requestStudentDetail.bind(this)),
).subscribe(this._studentList$);

A.withLatestFrom(B)用于在可观察到的A发出时从可观察到的B获取值,例如数组[a,b]格式。