{{ owner.name }} TS文件中的服务调用 getAwsOwners(-6ren">
gpt4 book ai didi

angular - 调用函数时清除 Observable 值

转载 作者:行者123 更新时间:2023-12-05 05:52:09 25 4
gpt4 key购买 nike

我有一个从服务中获取值的下拉菜单。

下拉菜单

<mat-select
*ngIf="selectedCloudTypeName === 'AWS'"
class="select--width--130"
[formControl]="awsOwnersControl"
placeholder="AWS Owners"
msInfiniteScroll
(infiniteScroll)="loadMoreAwsOwners()"
[complete]="currentAwsOwnerssDropdownOffset >= awsOwnersTotalCount"
>
<mat-option *ngFor="let owner of awsOwners$ | async" [value]="owner.id">
{{ owner.name }}
</mat-option>
</mat-select>

TS文件中的服务调用

getAwsOwners(offset = 0) {
this.isLoading$.next(true);
this.awsService
.getOwnersListForAws(this.selectedCredentialIdForCloudType, this.selectedPlatform, { offset, limit: 100 })
.subscribe(
(owners: PaginatedResult<CommonEnumValue[]>) => {
this.awsOwners.next(owners.data);
this.awsOwnersTotalCount = owners.totalCount;
this.isLoading$.next(false);
},
(error) => {
this.isLoading$.next(false);
this.alertify.error(error);
},
);

在 OnInit 钩子(Hook)中我使用了一个 Observable

this.awsOwners$ = this.awsOwners.asObservable().pipe(scan((acc, curr) => [...acc, ...curr], []));

我在文件中将其声明为属性

awsOwners = new BehaviorSubject<CommonEnumValue[]>([]);
awsOwners$: Observable<CommonEnumValue[]>;

问题是当我使用不同的“selectedPlatform”值调用 getAwsOnwers 函数时,旧数据仍然存在,新数据被附加。

我试图像这样清除 awsOwners 主题

this.awsOwners.next([]);

在我调用它之前,它确实清除了它并且新数据被附加到旧数据上,

有什么方法可以清除它吗?

我感觉到在扫描运算符中我需要清除“.acc”,因为它会累积值。

最佳答案

  1. this.awsOwners$ 管道中删除 scan
this.awsOwners$ = this.awsOwners.asObservable()
  1. this.selectedPlatform 设置为 Subject,并在更改时调用 getAwsOwners
this._selectedPlatform$ = new Subject()

get selectedPlatform$() {
// if platform is object you should provide comparing callback to distinctUntilChanged operator
return this._selectedPlatform$.asObservable.pipe(distinctUntilChanged(), tap(() =>
//make getAwsOwners() accept platform as an parameter and offset as a optional one.
this.getAwsOwners(platform);
))
}
  1. getAwsOwners 订阅方法中进行一些更改
  .subscribe(
(owners: PaginatedResult<CommonEnumValue[]>) => {
// always if offset === 0 you should reset owners state
this.awsOwners.next(offset ?
[...this.awsOwners.getValue(), ...owners.data] :
owners.data
);

this.awsOwnersTotalCount = owners.totalCount;
this.isLoading$.next(false);
},
(error) => {
this.isLoading$.next(false);
this.alertify.error(error);
},
);

关于angular - 调用函数时清除 Observable 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70262335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com