gpt4 book ai didi

angular - RxJS : Filter one observable using another observable

转载 作者:太空狗 更新时间:2023-10-29 19:32:32 25 4
gpt4 key购买 nike

我有一个流携带来自 API 响应的数据,另一个流发出需要从源流中过滤的值。

@Injectable({
providedIn: 'root'
})
export class SmpService {
private _smp$ = new ReplaySubject(1);
private _deleteSubject = new BehaviorSubject(null);

constructor(private http: HttpClient) {
const allSmp$ = this.loadSmp().pipe(map(list => list.map(item => item.id)));
const delete$ = this._deleteSubject.pipe(map(value => this.filterSmp(value)));

allSmp$
.pipe(
combineLatest(delete$, (notifications, xf) => {
return xf(notifications);
}),
tap(x => console.log('console ', x))
)
.subscribe(this._smp$);
}

loadSmp(): Observable<any> {
const contextPath = 'some_url';
const url = this.uriPrefix + contextPath;
return this.http.get(url).pipe(map((response: any) => response.notifications || []));
}

filterSmp(value) {
return notifications => notifications.filter(notification => value !== notification);
}

deleteSmp(subscribeItem) {
this._deleteSubject.next(subscribeItem);
}

getSmp(): Observable<any> {
return this._smp$.asObservable();
}
}

过滤正常。但是在页面加载时,我无法获得在页面上呈现的初始 API 响应。只有当我通过某些操作触发 deleteStream 时,我才会收到它。

有什么方法可以在没有触发 deleteStream 的情况下获取初始数据?

最佳答案

使用带有一些默认值的 BehaviorSubject 而不是 Subject。例如 null

private _deleteSubject = new BehaviorSubject(null);

BehaviorSubject 每次订阅时都会发出默认值。

关于angular - RxJS : Filter one observable using another observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51880242/

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