根据Angular中的场景执行Typescript函数

时间:2019-03-18 15:38:53

标签: angular typescript rxjs store angular-lifecycle-hooks

在我的应用程序中,一个组件中有两个组合框。 它们的默认值均为null

enter image description here

选择期间或用户时,该值将发送到商店。 这使您可以在不同的组成部分中使用期间和选定的用户。

要存储的Combobox.component:

  onSelectedWalletsPeriod(period: Period) {
    this.store.setSelectedWalletsPeriod(period);
  }

  onSelectedWalletsUser(user: User) {
    this.store.setSelectedWalletsUser(user);
  }

商店:

export class MystoreComponentStore {

    private selectedWalletsPeriodSubject = new BehaviorSubject<Period>(null);
    private selectedWalletsUserSubject = new BehaviorSubject<User>(null);

    public selectedWalletsPeriod$ = this.selectedWalletsPeriodSubject.asObservable();
    public selectedWalletsUser$ = this.selectedWalletsUserSubject.asObservable();

    constructor() {}

    setSelectedWalletsPeriod(period: Period) {
        this.selectedWalletsPeriodSubject.next(period);
        this.selectedWalletSubject.next(null);

        /# DEBUG #/
        console.log('selectedPeriod:', period);
    }

    setSelectedWalletsUser(user: User) {
        this.selectedWalletsUserSubject.next(user);
        this.selectedWalletSubject.next(null);

        /# DEBUG #/
        console.log('selectedUser:', user);
    }
}

存储到Result.component:

export class ResultComponent implements AfterViewInit {

  selectedWalletsPeriod: Period = null;
  selectedWalletsUser: User = null;

  constructor(public store: MystoreComponentStore) { }

  ngAfterViewInit() {
    this.store.selectedWalletsPeriod$.subscribe(period=> this.selectedWalletsPeriod = period);

    this.store.selectedWalletsUser$.subscribe(user=> this.selectedWalletsUser = user);
  }
}

要显示第二个组件的列表,我必须选择一个句点和一个用户。 在此之前,一切都可以正常运行。

但是我想做的是在选择用户和句点时执行一个功能。 更改两个组合框之一的值时,也会执行此功能。

该功能将允许我根据时间段和用户从数据库中检索钱包列表。

我不知道该怎么做。如果您有想法,我很感兴趣。

这是一个小例子:Stackblitz HERE

谢谢。

2 个答案:

答案 0 :(得分:3)

您可以使用combineLatest来监听select的最新值,然后过滤未同时设置两个值的那些值:

combineLatest(this.store.selectedWalletsPeriod$, this.store.selectedWalletsUser$)
    .pipe(filter(([period, user]) => period && user))
    .subscribe(([period, user]) => console.log('period=' + period + ',user=' + user));

上面的示例在设置两个值后应立即记录一个值。

另请参阅:documentation for combineLatest

答案 1 :(得分:1)

您可以压缩可观察对象:

https://www.learnrxjs.io/operators/combination/zip.html

如果两个可观察值都有值并且每次更改其中一个时,它将调用订阅。但是您需要通过“ not null”或类似方法来过滤可观察对象,因为您将行为主体初始化为null。

顺便说一句:您是否尝试过redux或ngrx(角度表示为redux)?您不需要实现自己的存储/动作处理/副作用/订阅逻辑。