Angular 2 Http, Observables and recursive requests

前端 未结 5 1379
梦毁少年i
梦毁少年i 2020-12-06 06:59

I have a REST endpoint that returns a list of items, max 1000 items at a time. If there are more than 1000 items, the response has HTTP status 206 and there\'s a Nex

5条回答
  •  孤街浪徒
    2020-12-06 07:26

    I got it working with minor tweaks to KwintenP's example:

    // service.ts
    
    getAllItems(): Observable {
      const getRange = (range?: string): Observable => {
        const headers: Headers = new Headers();
        if (range) {
          headers.set('Range', range);
        }
    
        return this.http.get('http://api/endpoint', { headers });
      };
    
      return getRange().expand((res: Response) => {
        if (res.status === 206) {
          const nextRange = res.headers.get('Next-Range');
    
          return getRange(nextRange);
        } else {
          return Observable.empty();
        }
      }).map((res: Response) => res.json());
    }
    

    In the component that subscribes to the Observable, I had to add a completed handler:

    // component.ts
    
    const temp = [];
    
    service.getAllItems().subscribe(
      items => {
        // page received, push items to temp
        temp.push.apply(temp, items);
      },
      err => {
        // handle error
      },
      () => {
        // completed, expose temp to component
        this.items = temp;
      }
    );
    

提交回复
热议问题