【发布时间】:2020-02-17 12:53:48
【问题描述】:
我有一个类商店如下:
import { BehaviorSubject, Observable } from 'rxjs'
export abstract class Store<T> {
private state: BehaviorSubject<T> = new BehaviorSubject((undefined as unknown) as T)
get(): Observable<T> {
return this.state.asObservable()
}
set(nextState: T) {
return this.state.next(nextState)
}
value() {
return this.state.getValue()
}
patch(params: Partial<T>) {
this.set({ ...this.value(), ...params })
}
abstract create(): void
}
还有我的 InstallationStore:
import { Store } from '../../store/store'
import { Installation } from '../domain/installation/installation'
import { from, Observable } from 'rxjs'
import { GetActiveInstallationUseCase } from '../../../features/planning/application/get-active-installation-use-case'
import { Injectable } from '@angular/core'
import { map, switchMap } from 'rxjs/operators'
import { LoginStore } from '../../../features/login/application/login-store'
interface State {
activeInstallation: Installation
}
@Injectable({
providedIn: 'root'
})
export class InstallationStore extends Store<State> {
constructor(
private readonly getActiveInstallationUseCase: GetActiveInstallationUseCase,
private readonly loginStore: LoginStore
) {
super()
this.create()
}
create(): void {
this.set({
activeInstallation: {
isDefault: true,
productionProfile: 'baz',
incomingProfile: 'foo',
id: 1,
energeticRole: 'bar',
name: ''
}
})
}
get(): Observable<State> {
return this.loginStore
.get()
.pipe(
switchMap(() => from(this.getActiveInstallationUseCase.execute()).pipe(map(x => ({ activeInstallation: x }))))
)
}
}
InstallationStore 在触发getActiveInstallationUseCase 两次的两个不同组件中被订阅get observable 两次。 getActiveInstallationUseCase.execute() 返回一个 Promise。我想做的是无论它有多少订阅者,它只会在用户登录时运行用例。
我试过share() 操作符没有成功,如下:
get(): Observable<State> {
return this.loginStore
.get()
.pipe(
switchMap(() => from(this.getActiveInstallationUseCase.execute()).pipe(map(x => ({ activeInstallation: x })))),
share()
)
}
和
get(): Observable<State> {
return this.loginStore
.get()
.pipe(
switchMap(() => from(this.getActiveInstallationUseCase.execute()).pipe(map(x => ({ activeInstallation: x }))), share()),
)
}
但它仍然运行两次。我检查了this.loginStore.get() 只发出一次事件,并尝试用shareReplay 替换share,但没有成功。
我已经复制了问题here。它调用了承诺 4 次,而我希望它只执行两次。添加share() 运算符使其工作,但在我的代码中没有,为什么?
【问题讨论】:
标签: javascript angular typescript rxjs