【问题标题】:Repeat a HTTP request as long as the condition is not met只要条件不满足就重复一个 HTTP 请求
【发布时间】:2017-09-19 21:08:11
【问题描述】:

我是 Angular 的初学者,这个问题可能很愚蠢或重复,很抱歉。

我的目标是只要 response.Done != true 就向 Web API 发送请求,这是我在 onInit 事件中从服务调用函数的代码:

export class FlightListComponent implements OnInit {

  flightSearchResult: FlightSearchResult;

  constructor(private service: FlightService) {
  }

  ngOnInit() {

    let guid = Guid.newGuid();

    this.service.getAll(guid).subscribe(response => {

      if (response.Done != true) {
        this.serveData(response);
        //  this.service.getAll(guid) ....
      }

    });
  }

在每个请求中,我还获得了一些数据,我需要通过serveData() 将它们合并到一个主变量中。但是我认为应该有更好的方法来处理 observable 在这种情况下我需要调用 getAll() 几次,只要 Done 不等于 true 并且事件在最后给我所有数据而不在每个请求中合并。每个传递的 Observable 的所有值如何合并到一个 Observable 中。

有什么解决办法吗?

【问题讨论】:

    标签: angular observable angular2-services


    【解决方案1】:

    这应该可行:

    ngOnInit() {
        let guid = Guid.newGuid();
        this.getAll(guid);      
    }
    
    getAll(guid: Guid) {
        this.service.getAll(guid).subscribe(response => {
            if (response.Done != true) {
               this.serveData(response);
               this.getAll(guid); 
            }
         });
     }
    

    不太了解这背后的逻辑,但您可能应该取消嵌套调用,因为您可能会重载您正在调用的 API。

    【讨论】:

      【解决方案2】:

      【讨论】:

      • 感谢您的回复。可以举个例子吗?
      【解决方案3】:

      我认为您正在寻找重试逻辑,示例如下-

      ngOnInit() {

      let guid = Guid.newGuid();
      
      this.service.getAll(guid).subscribe(response => {
      
        if (response.Done != true) {
          retryWaitTime = 10;
          retryCount = 2;
          counter++;
          if (counter < retryCount) {
              $timeout(function () {
                    this.serveData(response);
                    //  this.service.getAll(guid) ....
                   ,  retryWaitTime);
          } else {
            counter  = 0;
            //return error response
          }
      
        }
      
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-15
        • 2019-10-07
        • 2017-09-10
        • 1970-01-01
        • 1970-01-01
        • 2014-05-03
        • 2018-04-19
        • 2018-08-03
        相关资源
        最近更新 更多