为什么没有调用订阅

时间:2020-01-09 16:42:31

标签: javascript angular rxjs

我遇到以下问题是我做错了什么,因为未调用“ done”:

@Injectable({
  providedIn: 'root'
})

export class GetPersonsService {
  url:string="https://swapi.co/api/people/"
  persons:Person[];
  headers: HttpHeaders = new HttpHeaders()
    .set('Accept', 'application/json');
  constructor(private http: HttpClient) { }
  getPerson(personsId){
    return this.http.get<Person[]>(`${this.url}${personsId}/`,{headers:this.headers});
  }
  getAllPersons(){
    let numberOfPersons=88; 
    const response = [...Array(numberOfPersons).keys()].map(i => this.getPerson(i+1));
    return forkJoin(response).pipe(map(value=> value),share());
  }
}

和MainComponent

export class MainComponent implements OnInit {
      persons=[];
      constructor(private getPersons:GetPersonsService) { }

      ngOnInit() {
        this.getPersons.getAllPersons().subscribe(value=>{
          // this.persons.push(value);
          console.log("done");
        }
        );
      }
    }

这是怎么回事?为什么我无法在控制台中完成

1 个答案:

答案 0 :(得分:2)

您没有创建适当的数组...使用具有索引量的Array构造函数,将其填充为虚拟数据(空),然后使用map对其进行循环。 RxJS地图运算符没有用。

getAllPersons(){
  const numberOfPersons = 10; 
  const response = Array(numberOfPersons).fill(null).map((_, i) => this.getPerson(i+1));
  return forkJoin(response).pipe(share());
}

Strangler pattern

更新

似乎用户17不存在。在这种情况下,请在下面找到更新代码:

getAllPersons(){
  const numberOfPersons = 88; 
  const response = Array(numberOfPersons)
    .fill(null).map((_, i) => this.getPerson(i+1)
      .pipe(catchError(() => of(null))
    )
  );
  return forkJoin(response).pipe(share());
}