Angular 4重复点击多次获取http可观察数据

时间:2017-10-18 09:30:21

标签: angular http typescript rxjs observable

我有这项服务,它提供了来自API的数据作为Observable。 在我的组件中,如果用户双击get-method,数据将被多次推送到数组中。我是RxJs lib的新手,但我有一种感觉,可以使用.switchMap()修复它,使用BehaviorSubject或者使用|异步管?

“hitsArray”-array,包含HTML中的数据作为ngFor - 来自http get的responsedata被推送到数组中超过1次,如果用户反复“spams”该函数点击。

服务:

  getStories(page: string, hits: string, feed: string): Observable<any> {
    return this.getToken()
      .flatMap(idToken => {
        let headers = new Headers();
        headers.set('user_token', idToken);
        let params = new URLSearchParams();
        params.set('page', page)
        params.set('hits', hits)
        params.set('feed', feed)
        return this.http
          .get(`${this.apiUrl}/stories`, { params: params, headers: headers })
          .map((res: Response) => {
            //console.log(response);
            console.log("params: " + params);
            const data = res.json();
            return data;
          });
      })
      .catch(this.handleError);
  }

成分:

private getStories(page, hits, feed) {
    feed = this.feed;
    this.storiesService.getStories(this.page, this.hits, this.feed)
      .subscribe(
      (data) => {
        console.log(data);
        if (!data || data.hits == 0 || data.hits < 6) {
          this.finished = true;
          console.log("No more hits :(")
        } else {
          this.finished = false;
          for (let story of data.hits) {
            this.hitsArray.push(story);
            console.log("Feed me!")
          }
        }
      })
    console.log("side: " + this.page)
  }

  getInitialFeed(feed) {
    this.hitsArray.length = 0;
    this.page = 0;
    this.feed = feed;
    this.data = [];
    this.getStories(0, this.feed, '6');
  }

  onScroll() {
    console.log("Scrolling!")
    this.scrollStories()
  }

  private scrollStories() {
    this.page++; //SCROLLING
    if (this.page > 0) {
      console.log(this.page)
      this.getStories(this.page, this.hits, this.feed);
    }
  }

HTML ngFor循环:

<div class="col-xs col-sm col-md-4 col-lg-4" *ngFor="let story of hitsArray" (click)="getSpecificStory(story)">

HTML功能“Feed”调用:

  <a routerLink="/discover/curated" routerLinkActive="active" (click)="getInitialFeed('curated')">Curated</a>
  <a routerLink="/discover/trending" routerLinkActive="active" (click)="getInitialFeed('trending')">Trending</a>
  <a routerLink="/discover/latest" routerLinkActive="active" (click)="getInitialFeed('latest')">Latest</a>

1 个答案:

答案 0 :(得分:1)

如果尚未返回数据,则switchmap只能阻止数据的返回。您的代码完全正常,并按照您的要求执行操作:当用户单击时,您发送数据请求。通过清空hitsArray this.hitsArray = [];

可以轻松解决您的问题