【问题标题】:angular 4 and rxjs - preventing canceled requests from hitting the serverangular 4 和 rxjs - 防止取消的请求到达服务器
【发布时间】:2018-02-04 18:24:02
【问题描述】:

我有一个表,我希望每次用户将鼠标悬停在其中一行上方时触发一个 http 请求。但是,我只想在用户在该行上方花费至少 200 毫秒时才发送请求。我知道switchMap 允许您取消http 请求,但这并不能阻止已经在途中的http 请求访问服务器,是吗?我是否应该实现一些其他的去抖动逻辑,例如使用SubjectdebounceTime

谢谢。

【问题讨论】:

  • 我不认为有办法这样做,但我想错了。
  • Rx.Observable.fromEvent(dom,'mouseover').timer(200).switchMap(()=>fetch('www..')).subscribe(),但还是赢了'如果有 http 就不要取消

标签: angular rxjs


【解决方案1】:

正如你所指出的,switchMap 会杀死之前订阅的 observable。

在上面的评论中,Fan Cheung 正在使用 fetch。 Fetch 不支持取消。

Angulars HttpClient 确实支持取消 http 请求,所以你很幸运。

根据您获得悬停事件的方式,您可以以不同的方式处理它。 但是我可以给你看一个使用主题的版本

(未经测试的代码)

@Component({
    template: `
        <table>
            <tr
                *ngFor="let item of items"
                // on hover we pass the current item to the mouseOver handler
                (mouseover)="mouseOver(item)"
            >
                <td>{{item}}</td>
            </tr>
        </table>

        // if there is a hovered item we show it
        <div *ngIf="hovered$ | async; let hoverItem">
            {{hoverItem}}
        </div>
    `
})
export class TableComponent extends Component {

    items = ['one', 'two', 'three'];

    // a stream of hovered items
    hoverSubject = new Subject();

    // a stream of requested hover items
    // that have been debounced
    hoverItem$: Observable<string>;

    constructor() {
        this.hoverItem$ = this.hoverSubject.pipe(
            // only let items pass every 200ms
            debounceTime(200),

            // only pass items that are different from the previous ones
            distinctUntilChanged,

            // do the request
            switchMap(item => this.http.get(`https://something`)),
        );
    }

    // emit new hovered items into the hoverSubject
    mouseOver(item: string) {
        this.hoverSubject.emit(item);
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-07
    • 2020-01-20
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多