繁体   English   中英

如何在 Angular 2 中取消 HTTPRequest?

[英]How to cancel a HTTPRequest in Angular 2?

如何在 Angular 2 中取消 HTTPRequest?

我只知道如何拒绝请求承诺。

return new Promise((resolve, reject) => {
    this.currentLoading.set(url, {resolve, reject});

    this.http.get(url, {headers: reqHeaders})
        .subscribe(
            (res) => {
                res = res.json();

                this.currentLoading.delete(url);
                this.cache.set(url, res);

                resolve(res);
            }
        );
});

您可以使用以下简单的解决方案:

if ( this.subscription ) {
   this.subscription.unsubscribe();
}
this.subscription = this.http.get( 'awesomeApi' )
 .subscribe((res)=> {
  // your awesome code..
})

你可以打电话unsubscribe

let sub = this.http.get(url, {headers: reqHeaders})
            .subscribe(
                (res) => {
                    res = res.json();

                    this.currentLoading.delete(url);
                    this.cache.set(url, res);

                    resolve(res);
                }
            );

sub.unsubscribe();

更多信息在这里: http ://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http

您可以在 observable 上使用 SwitchMap ,它将取消任何先前请求的响应,并且只请求最新的:

https://www.learnrxjs.io/operators/transformation/switchmap.html

聚会有点晚了,但这是我的看法:

import { Injectable } from '@angular/core'
import { Http } from '@angular/http'
import { Observable } from 'rxjs/Observable'
import { Subscriber } from 'rxjs/Subscriber'

@Injectable ()
export class SomeHttpServiceService {
  private subscriber: Subscriber<any>
  constructor(private http: Http){ }

  public cancelableRequest() {
    let o = new Observable(obs => subscriber = obs)
    return this.http.get('someurl').takeUntil(o)
      .toPromise() //I dont like observables
      .then(res => {
        o.unsubscribe
        return res
      })
  }
  public cancelRequest() {
    subscriber.error('whatever')
  }
}

这允许您手动取消请求。 我有时会得到一个 observable 或 promise 来改变页面上的结果。 如果请求是自动启动的(用户没有在 x 毫秒的字段中输入任何内容)能够中止请求是很好的(用户突然再次输入内容)......

takeUntil 也应该使用简单的超时(Observable.timer),如果这是您正在寻找的https://www.learnrxjs.io/learn-rxjs/operators/filtering/takeuntil

使用switchMap [docs] ,它将取消所有正在进行的请求并仅使用最新的。

get(endpoint: string): Observable<any> {
        const headers: Observable<{url: string, headers: HttpHeaders}> = this.getConfig();
        return headers.pipe(
            switchMap(obj => this.http.get(`${obj.url}${endpoint}`, { headers: obj.headers, params: params }) ),
            shareReplay(1)
        );
    }

shareReplay将为任何迟到的订阅者发出最新的值。

这是一个很棒的线程,我还有更多信息要提供。 我有一个可能会持续很长时间的 API 调用。 所以我需要前一个请求以超时取消。 我今天才发现我可以在管道函数中添加一个timeout运算符。 一旦超时完成其计数,这将取消先前的 HTTP 请求。

例子...

return this.exampleHttpRequest()
  .pipe(
    timeout(3000),
    catchError(err => console.log(error)
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM