行为主题只有在有新事物的情况下才返回
我有以下问题,当我调用getstudentslist函数时,它将转到服务器以查找所需的新值,但是行为主题再次返回当前值(这会导致我问题,因为它加载了视图,将视图加载到先前的值中)当我等待服务器信息返回时。 我该如何避免这种行为?
getStudentsList(params): Observable<StudentsListGrid> {
if (this.studentListSubject$ === undefined) {
this.studentListSubject$ = new BehaviorSubject<StudentListGrid>(null);
}
this.refetchStudentList(params);
return this.studentListSubject$.asObservable().pipe(filter((value) => value !== null));
}
refetchStudentList(gridParams) {
const subscription = this.http.post<StudentListGrid>(this.baseUrl + 'GetStudents', {gridParams} ,httpOptions).pipe(map(data => this.setDefaultValuesToStudent(data))).subscribe(
(response) => {
this.studentListSubject$.next(response);
subscription.unsubscribe();
});
}
I have the following problem, when I call the getStudentsList function, it goes to the server to find the new values that I need, but the behaviorSubject returns the current value again (This causes me problems because it load the view with the previous values) while I wait for the server information to return.
How can I do to avoid this behavior?
getStudentsList(params): Observable<StudentsListGrid> {
if (this.studentListSubject$ === undefined) {
this.studentListSubject$ = new BehaviorSubject<StudentListGrid>(null);
}
this.refetchStudentList(params);
return this.studentListSubject$.asObservable().pipe(filter((value) => value !== null));
}
refetchStudentList(gridParams) {
const subscription = this.http.post<StudentListGrid>(this.baseUrl + 'GetStudents', {gridParams} ,httpOptions).pipe(map(data => this.setDefaultValuesToStudent(data))).subscribe(
(response) => {
this.studentListSubject$.next(response);
subscription.unsubscribe();
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基于
解决方案1
以进行快速解决方案时发出其当前值,您可以在 getSudentslistlist 函数中返回可观察到的null。
中 通过null通过null来清空行为的最后一个值,因此此函数的返回始终返回新的值。
解决方案2
另一种方法(更好的方法)是使用rxjs库中的不同的企业,我想您的名字在每个响应中都会有所不同:
希望此答案对您有所帮助。
Based on the definition of BehaviorSubject from doc
Solution 1
For a quick solution, you can set null before you return Observable in the getStudentsList function:
The reason is you empty the last value of BehaviorSubject by passing null so the return of this function always returns a fresh value.
Solution 2
Another way (better way) is to use distinctUntilChanged from RxJs library, I suppose your name become different in each response:
I hope this answer helps you.
通常,您不想为了更新另一个可观察到的主题而订阅某些东西。取而代之的是结局的连锁事件。
现在,无论消耗
学生列表$
什么都将获得最后的结果,并在每次刷新时都会收到新的学生列表。As a rule, you do not want to subscribe to something for the purposes of updating another observable or subject. Instead, chain events to outcomes.
Now, whatever consumes
studentList$
will receive the last-emitted result, plus a new student list every time it's refreshed.