typescript - Angular 可观察对象:在这个解决方案中,如何向 callWS() 方法传递参数?
使用和重置 shareReplay 的这个解决方案来自:RxJS shareReplay:如何重置其值?
private _refreshProfile$ = new BehaviorSubject<void>(undefined);
public profile$: Observable<Customer> = _refreshProfile$
.pipe(
switchMapTo(this.callWS()),
shareReplay(1),
);
public refreshProfile() {
this._refreshProfile$.next();
}
答案#1
你可以使用 switchMap。用法如下:
private _refreshProfile$ = new BehaviorSubject<number>(0);
public profile$: Observable<Customer> = _refreshProfile$
.pipe(
switchMap(userId => this.callWS(userId)),
shareReplay(1),
);
public refreshProfile(userId: number) {
this._refreshProfile$.next(userId);
}
this.profile$.subscribe(console.log);
this.refreshProfile(20); // 20 will be passed as userId to callWS
StackBlitz 参考:https://stackblitz.com/edit/angular-ivy-ezaxsk?file=src/app/hello.component.ts
