Angular Observables:在这个解决方案中,如何将参数传递给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();
}

您可以使用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

最新更新