取消订阅请求Angular

时间:2020-03-02 12:27:31

标签: angular http

我正在发送有关角度到后端部分的所有请求。当我在输入中输入新值时,我用不同的参数发送相同的请求,由于服务器的响应,数据被更新到前端部分。如果已经发送了新请求,我如何实现取消等待旧请求?为了不为每个请求呈现组件,而是仅为最后一个呈现组件?

一些代码:

    getNotes() {
    this.isLoaded = false;
    this.noteService.getNotes(this.page, this.sortBy, this.searchNoteValue)
        .subscribe((notes: Note[]) => {
            this.userNotes = notes;
            this.isLoaded = true;
        }});
    }

2 个答案:

答案 0 :(得分:0)

一种简单的方法是定义属性notesSubscription:订阅

import { Subscription } from 'rxjs';
...
notesSubscription: Subscription;

并修改您的getNotes方法

getNotes() {
this.isLoaded = false;
if (this.notesSubscription) {
    this.notesSubscription.unsubscribe();
}
this.notesSubscription = this.noteService.getNotes(this.page, this.sortBy, this.searchNoteValue)
    .subscribe((notes: Note[]) => {
        this.userNotes = notes;
        this.isLoaded = true;
    }});
}

致谢

答案 1 :(得分:0)

我建议使用RxJS的switchMap运算符。您可以订阅可观察的notes$并根据需要触发所有请求。

免责声明:代码未经测试,仅是为了说明编程方式

private _getNotesTrigger = new Subject<{page:string,sortBy:string, searchNoteValue:string}>();

public notes$ : Observable<Note[]> = this._getNotesTrigger
       .pipe(switchMap(theParams => this.noteService.getNotes(theParams));

getNotes() {
    this.isLoaded = false;
    this._getNotesTrigger.next(this.page, this.sortBy, this.searchNoteValue)
}