angular - 只要不满足条件就重复HTTP请求

标签 angular observable angular2-services

我是 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,在这种情况下,只要 Done 不等于 true,我就需要多次调用 getAll(),并且 event 在最后给我所有数据,而无需合并每个请求。每个传递的 Observable 的所有值如何合并到单个 Observable 中。

有什么解决办法吗?

最佳答案

这应该有效:

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。

关于angular - 只要不满足条件就重复HTTP请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46309775/

相关文章:

Angular BehaviorSubject 订阅只触发一次

swift - RxSwift 扩展 Observable 泛型问题

json - autopulous-xdom2jso 中的“xdom 未定义”错误

Typescript getter 和 setter 错误

javascript - http请求的 Angular 文件上传方法

html - 剪辑路径在 Safari 上无法正常工作

javascript - 类型错误 : Cannot read property 'match' of undefined 中的错误

angular - Googlebot 可以读取此页面上的哪些元素?

Angular 2/ typescript : How to access observable property in component

Angular 2 : passing object with nested object to child component