离子极限 API 调用

Ionic limit API calls

我在使用第 3 方库的 Ionic 中使用 Spotify 的 API(我没有直接从我的代码执行 HTTP 查询)并且我试图限制每秒请求的数量发送。

我的期望:

我不是 Ionic 方面的专家,也不是 Angular。 我试过这个:

const apiCalls = [];

//in a for loop
apiCalls.push(fromPromise(this.spotifyApi.getArtistRelatedArtists(sourceArtist.mbid)).delay(this.apiDelay).toPromise());

//then
concat(...apiCalls).subscribe(

好像没有什么效果,比如我发了20个apiDelay为1秒的请求,不到2秒就全部完成了。

我试过使用库,比如这个: simple-rate-limiter 但是它们应该与 'require' 一起使用,而 Ionic 抱怨说:

Could not find a declaration file for module

如何在 Ionic 中延迟对外部 API 的请求?

或许你可以试试下面的简单方法,demo https://stackblitz.com/edit/angular-http-client-kfnniw

// mock some random requests
for (let i = 0; i < 10; i++) {
  setTimeout(() => this.httpCalls.push({
    id: i,
    request: this.http.get<any[]>(this.apiUrl)
  }), Math.random() * 5000);
}

// handle queue
let interval = setInterval(() => {
  let toRun = this.httpCalls.splice(0, 5);
  for (let i = 0; i < toRun.length; i++) {
    ((r) => {
      let s = new Subject();
      r.request.subscribe(s);
      this.httpResponses.push({ id: r.id, subject: s });
    })(toRun[i]);
  }
}, 1000);

// in some other places, process actual requests
setInterval(() => {
  let r = this.httpResponses.splice(0, this.httpResponses.length);
  for (let i = 0; i < r.length; i++) {
    r[i].subject.subscribe(data => {
      console.log(`finished request ${r[i].id}`);
    });
  }
}, 1000);

我通过将代码更改为类似这样的方式解决了这个问题。 它基本上使用 setTimeout 来延迟 API 调用的开始。

const apiCalls = [];
let i = 0;

//in a for loop
apiCalls.push(this.getRelatedArtistsWithDelay(i * this.apiDelay, sourceArtist.id[this.PROVIDER]));
i++;

//then
concat(...apiCalls).subscribe(

//and the getRelatedArtistsWithDelay function calls the API with a delayed start
  private getRelatedArtistsWithDelay(delay, artistId){
    return new Promise(resolve => {
      setTimeout(() => {
        this.spotifyApi.getArtistRelatedArtists(artistId).then((data) => {
          resolve(data);
        })
      },
      delay)
    });
  }