网站搜索

javascript - http post 订阅和 try catch


我使用 Angular2 的 http.post,有时头信息不会发送到 CORS 服务器。所以我想尝试直到请求成功。但这段代码会无限循环吗?

 var headers = new Headers();
 headers.append('Content-Type', 'text/plain');

 this.again = true;
        while (this.again==true) {
           http.post('https://localhost:44300/account/getip', "", { headers: headers })
                .subscribe(
                (res2) => {
                    try {
                        this.ip = res2.json();
                        this.ipstr = this.ip.replace(/\./g, '-');
                        this.again = false;
                     }
                    catch (err) {
                        console.error(err);
                    }
                }
                );
        }

答案#1

如果你想捕获请求中的错误,你可以选择以下方法之一:

  • 使用 subscribe 方法的第二个回调:

    http.post('https://localhost:44300/account/getip', "", { headers: headers })
            .subscribe(
              (res2) => {
                (...)
              },
              (error) => {
                (...)
              }
            );
    }
    
  • 使用 catch 操作符:

    http.post('https://localhost:44300/account/getip', "", { headers: headers })
            .catch((error) => {
              (...)
            })
            .subscribe(
              (res2) => {
                (...)
              }
            );
    }
    

关于重试请求,你可以这样利用 retry 操作符(配合 timeout 使用):

this.http.get('https://localhost:44300/account/getip',
          { search: params })
    .retryWhen(error => error.delay(500))
    .timeout(2000, return new Error('delay exceeded'))
    .map(res => res.json().postalCodes);

你可以看到使用 delay 来在执行新请求之前等待一段时间...

这篇文章你也可能会感兴趣:

  • https://jaxenter.com/reactive-programming-http-and-angular-2-124560.html

答案#2

您可以使用 retry 操作符:

http.post('https://localhost:44300/account/getip', "", { headers: headers })
.retry(3)              
.subscribe((res2) => {
  this.ip = res2.json();
  this.ipstr = this.ip.replace(/\./g, '-');
})