为什么不调用订阅

问题描述 投票:0回答:1

我遇到以下问题,因为没有调用“ 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");
        }
        );
      }
    }

这里发生了什么?为什么我没有在控制台中完成工作

javascript angular rxjs
1个回答
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());
}

https://stackblitz.com/edit/angular-ocbfoy

UPDATE

似乎用户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());
}

-1
投票

您的订阅正在被调用,但是从它的声音来看,您得到一个错误,因此将调用error()而不是next()。

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

这至少应该向您显示您的订阅正在运行,但是不成功。

订阅最多需要三个参数:

subscribe(next(), error(), complete());

https://rxjs-dev.firebaseapp.com/guide/observable

© www.soinside.com 2019 - 2024. All rights reserved.