1 回答
TA贡献1770条经验 获得超3个赞
更新
所以问题实际上出在打字上。您不需要[]在Generation任何地方之后添加。因为没有任何地方可以让 API 用世代数组来响应。
因此,[]从getGeneration1服务中 HTTP 的类型化响应的返回类型和类型中删除。
请注意,Typescript 中的类型仅用于编译时,它不会影响运行时中的任何内容,只是为了确保您使用正确的引用并在运行前检测错误。
我在这里添加 getGeneration 函数:
getGeneration1(): Observable<Generation> {
return this.http.get<Generation>(this.GetGenerationURL1)
.pipe(
tap(_ => console.log('fetched generations')),
catchError(this.handleError<Generation>('getGeneration1', []))
);
}
getGeneration2(): Observable<Generation> {
return this.http.get<Generation>(this.GetGenerationURL2)
.pipe(
tap(_ => console.log('fetched generations')),
catchError(this.handleError<Generation>('getGeneration2', []))
);
}
在组件中,您需要像这样重构它:
export class PokeApp implements OnInit {
gen1: Generation;
gen2: Generation;
generation : Generation;
constructor(private http: HttpClient, private gService:GenerationService) {
}
ngOnInit(){
this.getGeneration1();
this.getGeneration2();
this.gService.getPokemon_Species(this.generation.name);
}
getGeneration1(): void{
this.gService.getGeneration1().subscribe(gen =>{
this.gen1 = gen
this.generation = gen;
});
}
getGeneration2(): void{
this.gService.getGeneration2().subscribe(gen => this.gen2 = gen);
}
这是为了防止您仍然需要组件中的代码在不链接我在旧答案中提供的响应的情况下工作,但我建议重构您的代码,如下所示:
getGenerations() {
this.gService.getGeneration1()
.pipe(mergeMap(gen => {
this.generation = gen;
return this.gService.getGeneration2();
}))
.pipe(mergeMap(gen => {
return this.gService.getPokemon_Species(this.generation.name);
}))
.subscribe(response => console.log(response));
}
旧答案
您很需要使用mergeMap。它应该是这样的:
getGenerations() {
this.gService.getGeneration1()
.pipe(mergeMap(gen => {
this.gen1 = gen;
this.generation = gen[0];
return this.gService.getGeneration2();
}))
.pipe(mergeMap(gen => {
this.gen2 = gen;
return this.gService.getPokemon_Species(this.generation.name);
}))
.subscribe(response => console.log(response));
}
添加回答
举报