【问题标题】:Ionic 2: stop an http request离子2:停止http请求
【发布时间】:2017-02-23 08:19:26
【问题描述】:

我的提供商为http.get 请求提供了一个 API:

join(){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('x-access-token',this.getToken());
    return Observable.create(observer =>{
        this.http.get('/localhost/chat/'+this.room,{headers : headers})
                .map(res => res.json())
                .subscribe(
                    data=>{                         
                        observer.next(data);
                    },
                    (err) =>{
                        observer.error(err);
                    }
                );
    })
}

我的page.ts 只是循环使用这个API:

join(){
    this.myProvider.join().subscribe(
        (data)=>{
            if(data.success){
                ... /* doing smt */ ....
                this.join();
            }else{
                this.message=data.message;
                //TBD sleep....
                //this.join();
            }
        },
        (err) => {
            this.message="Connectivity with server Lost...";
        });
  }

我的问题是:我想在page.ts 中写一个函数来停止这个循环。 如何终止待处理的 get 请求?

一个不起作用的解决方案是 我试图在page.ts 中保留指向可观察对象的指针:

export class Page {
    ...
    join_channel: any;
  join(){
    this.join_channel = this.myProvider.join().subscribe(
        (data)=>{
            ...
                this.join();
            ...

然后我通过调用this.join_channel.unsubscribe() 我想关闭请求,所以在我的情况下:

  ionViewWillLeave() {
    this.join_channel.unsubscribe();
    delete this;
  }

但即使取消订阅,get 请求仍处于等待状态;因此,当我尝试再次在我的页面中输入时,新的join() 在第一步无法收到 http.get 响应,因为该答案将在之前用于仍待处理的上一个请求。

【问题讨论】:

  • 你做到了吗?
  • 找到的解决办法是把观察者留在我的page.ts: export class Page { ... join_channel: any; join(){ this.join_channel = this.myProvider.join().subscribe( (data)=>{ ... this.join(); ... 然后我可以通过 this.join_channel.unsubscribe 终止获取请求(). 就我而言:ionViewWillLeave() { this.join_channel.unsubscribe(); delete this; }

标签: http ionic2 rxjs


【解决方案1】:

使用 rxjs 的超时时间

this.http.get(API)
    .timeout(2000)
    .map(res => res.json()).subscribe((data) => {
      return data;
    },
      (err) => {
        return err;
      }
    );

别忘了导入import 'rxjs/add/operator/timeout';

【讨论】:

  • 但是超时自动杀死请求;我需要一些不同的东西:应该在ionViewWillLeave() 上关闭请求
  • 我认为它可以工作,但实际上 unsubscribe() 并没有真正杀死 http.get
【解决方案2】:

如果你使用angular 6,你必须使用

管道(超时(2000))

this.http.get(API)
    .pipe(timeout(2000))
    .map(res => res.json()).subscribe((data) => {
      return data;
    },
      (err) => {
        return err;
      }
    );

【讨论】:

    猜你喜欢
    • 2016-12-11
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 2017-02-09
    相关资源
    最近更新 更多