【问题标题】:Angular 2 Observable.forkJoin with for loopAngular 2 Observable.forkJoin 与 for 循环
【发布时间】:2017-08-01 13:16:05
【问题描述】:

这就是我现在的工作方式:

getTwoObjectById(url1: string, id1: string, url2: string, id2): any{
  return Observable.forkJoin(
    this.http.get(url1 + `/${id1}`, this.jsonWebToken()).map(res => 
      res.json()),
    this.http.get(url2 + `/${id2}`, this.jsonWebToken()).map(res => 
      res.json())
  );
}

我想用id1, url1, id2, url2, id3, url3...来防止这种功能...

我正在尝试编写一个函数,该函数应将一个 ID 数组和一个 URL 数组作为参数。使用Observable.forkJoin,for 循环应该执行每个请求 getById 到 Array 中的 Backend-URL。 我的问题在于 for 循环

getObjectsById(ids: Array<string>, urls: Array<string>): Observable<any>{
  return Observable.forkJoin(

  for(let i = 0; i++; i<ids.length) {

     this.http.get(urls[i] + `/${ids[i]}`, this.jsonWebToken()).map(res => res.json());

  }

 )
}  

我该怎么做?

【问题讨论】:

标签: angular rest typescript


【解决方案1】:

试试这个

inputObject = [1, 2, 3, 4];


getObjectsById() {
    let observableBatch = [];

    this.inputObject.forEach((key) => {
      observableBatch.push(this.http.get(url+key).map((res) => res.json()));
    });

    return Observable.forkJoin(observableBatch);
  }

【讨论】:

    猜你喜欢
    • 2017-07-09
    • 2020-07-10
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多