下面的代码返回一个空数组,我很难理解为什么。从返回Observable将对象推到数组的标准做法是什么?
在jobServices.ts中:
getCities(city){
return this.http.get(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=70d86e78cabf44f710fd89936c709750`)
}
在Home.ts
cities = ["Atlanta", "Chicago", "New York", "Los Angeles", "San
Diego", "Athens", "Miami", "Nashville", "Austin", "Amsterdam",
"Paris" ]
citiesPayload = []
constructor(public jobService: JobService) { }
ngOnInit() {
this.returnCities();
}
returnCities(){
for (var i = 0; i < this.cities.length; i++){
this.jobService.getCities(this.cities[i])
.subscribe(city => {
this.citiesPayload.push(city);
});
}
console.log(this.citiesPayload)
}
答案 0 :(得分:3)
尝试类似的方法,您需要将HTTP请求添加到数组中,然后使用类似forkJoin的运算符。然后,您可以subscribe
到新返回的流。
import {
forkJoin
} from 'rxjs';
class ExampleClass {
cities = [
"Atlanta",
"Chicago",
"New York",
"Los Angeles",
"San Diego",
"Athens",
"Miami",
"Nashville",
"Austin",
"Amsterdam",
"Paris"
];
constructor(public jobService: JobService) {}
ngOnInit() {
this.returnCities()
}
returnCities() {
const cityObservables = [];
for (var i = 0; i < this.cities.length; i++) {
cityObservables.push(this.jobService.getCities(this.cities[i]));
}
forkJoin(cityObservables).subscribe(resp => {
// city data here
console.log(resp);
});
}
getCities(city) {
return this.http.get(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=70d86e78cabf44f710fd89936c709750`)
}
}
添加一个stackblitz-demo是@RichardMatsen和@ eric99的建议。
import {
Component,
OnInit
} from '@angular/core';
import {
HttpClient
} from '@angular/common/http';
import {
Observable,
forkJoin,
of
} from 'rxjs';
import {
catchError
} from 'rxjs/operators';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
todos: number[] = [1, 3, 5, 7, 9];
viewValues: Todo[];
constructor(private http: HttpClient) {}
ngOnInit() {
this.getTodos();
}
getTodos() {
const todos = this.todos.map(t => this.http.get < Todo > (`https://jsonplaceholder.typicode.com/todos/${t}`));
forkJoin(todos).pipe(catchError(err => of (err))).subscribe(resp => this.viewValues = resp);
}
}
export interface Todo {
userId: number;
id: number;
title: string;
completed: boolean;
}