简体   繁体   English

可观察的数组 angular rxjs

[英]Array of observables angular rxjs

I have following code:我有以下代码:

export class GetPersonsService {
  url="https://swapi.co/api/people/";
  personsObservables;
  headers: HttpHeaders = new HttpHeaders()
    .set('Accept', 'application/json');
  constructor(private http:HttpClient) { }
  getPerson(personIndex){
    return this.http.get<Person>(`${this.url}${personIndex}`,{headers:this.headers});
  }
  getPersons(){
    for(let i=0;i<10;i++){
      this.personsObservables.push(this.getPerson(i));
    }
    console.log(this.personsObservables);
    return forkJoin(this.personsObservables);
  }
}

and I don't understand why this.personsObservables is undefined because If I invoke getPerson(1) I am getting observable.And the next question how to maintain api if there are 10/100 or more items and I want to detect how many are them.我不明白为什么 this.personsObservables 是未定义的,因为如果我调用 getPerson(1) 我正在观察。下一个问题如果有 10/100 或更多项目,如何维护 api 并且我想检测有多少是他们。

It is necessary:有必要:

  • at first to initialize an array of url to avoid undefined error首先初始化一个url数组以避免undefined错误
  • then await API call getPerson (i)`然后await API 调用getPerson (i)`
  • then you can use forkJoin .那么你可以使用forkJoin

So the code should look like this:所以代码应该是这样的:

const personsObservables = [];

async getPersons(){
    for(let i=0;i<10;i++){
        this.personsObservables.push(await this.getPerson(i));
    }
    console.log(this.personsObservables);
    return forkJoin(this.personsObservables);
}

Let me show an example:让我举个例子:

const request1 = this.http.get('https://restcountries.eu/rest/v1/name/india');
const request2 = this.http.get('https://restcountries.eu/rest/v1/name/us');
const request3 = this.http.get('https://restcountries.eu/rest/v1/name/ame');
const request4 = this.http.get('https://restcountries.eu/rest/v1/name/ja');

const requestArray = [];
requestArray.push(request1);
requestArray.push(request2);
requestArray.push(request3);
requestArray.push(request4);

forkJoin(requestArray).subscribe(results => {
  console.log(results);
  this.response = results;
});

All results are ordered accordingly pushed items into requestArray.所有结果都按顺序排列,将项目推送到requestArray. It can be seen in a stackblitz example .它可以在stackblitz 示例中看到。

Please do as below.请按以下步骤操作。

export class GetPersonsService {
  headers: HttpHeaders = new HttpHeaders().set("Accept", "application/json");
  url = "https://swapi.co/api/people/";
  personsObservables: Person[] = [];

  constructor(private http: HttpClient) {}

  getPerson(personIndex: number) {
    this.http
      .get<Person>(`${this.url}${personIndex}`, { headers: this.headers })
      .subscribe(data => {
        this.personsObservables.push(data);
      });
  }

  getPersons() {
    for (let i = 0; i < 10; i++) {
      this.getPerson(i);
    }
    console.log(this.personsObservables);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM