Angular 如何映射从Http调用返回的Observable

Angular 如何映射从Http调用返回的Observable,angular,rxjs,observable,angular-httpclient,Angular,Rxjs,Observable,Angular Httpclient,下面的代码返回一个空数组,我很难理解为什么。将对象从可观测返回推送到阵列的标准做法是什么 在jobServices.ts中: getCities(city){ return this.http.get(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=70d86e78cabf44f710fd89936c709750`) } 在家里 cities=[“亚特兰大”、“芝加哥”、“纽约”、“洛杉矶”、“旧金

下面的代码返回一个空数组,我很难理解为什么。将对象从可观测返回推送到阵列的标准做法是什么

在jobServices.ts中:

 getCities(city){
  return this.http.get(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=70d86e78cabf44f710fd89936c709750`)
 }
在家里

cities=[“亚特兰大”、“芝加哥”、“纽约”、“洛杉矶”、“旧金山”
迭戈、雅典、迈阿密、纳什维尔、奥斯汀、阿姆斯特丹、,
“巴黎”]
citiesPayload=[]
构造函数(公共工作服务:工作服务){}
恩戈尼尼特(){
这个。返回城市();
}
返回城市(){
for(var i=0;i{
此.citiesPayload.push(城市);
});
}
console.log(this.citiesPayload)
}

尝试类似的方法,您需要将HTTP请求添加到数组中,然后使用类似的运算符。然后您可以订阅新返回的流

导入{
分叉连接
}来自‘rxjs’;
类示例类{
城市=[
“亚特兰大”,
“芝加哥”,
“纽约”,
“洛杉矶”,
“圣地亚哥”,
“雅典”,
“迈阿密”,
“纳什维尔”,
“奥斯汀”,
“阿姆斯特丹”,
“巴黎”
];
构造函数(公共工作服务:工作服务){}
恩戈尼尼特(){
这是()
}
返回城市(){
const cityObservables=[];
for(var i=0;i{
//这里是城市数据
控制台日志(resp);
});
}
getCities(城市){
返回this.http.get(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=70d86e78cabf44f710fd89936c709750`)
}
}
添加一个包含@RichardMatsen和@eric99的建议

导入{
组成部分,
奥尼特
}从“@angular/core”开始;
进口{
HttpClient
}来自“@angular/common/http”;
进口{
可见的,
forkJoin,
属于
}来自‘rxjs’;
进口{
捕捉错误
}来自“rxjs/运营商”;
@组成部分({
选择器:“我的应用程序”,
templateUrl:“./app.component.html”,
样式URL:['./app.component.css']
})
导出类AppComponent实现OnInit{
待办事项:数字[]=[1,3,5,7,9];
视图值:Todo[];
构造函数(私有http:HttpClient){}
恩戈尼尼特(){
这个。getTodos();
}
getTodos(){
const todos=this.todos.map(t=>this.http.get(`https://jsonplaceholder.typicode.com/todos/${t}`);
forkJoin(todos).pipe(catchError(err=>of(err))).subscribe(resp=>this.viewValues=resp);
}
}
导出接口Todo{
userId:number;
id:编号;
标题:字符串;
完成:布尔;
}

也许可以像这样使用Array.map
const cityObservables=this.cities.map(city=>this.jobService.getCities(city))
或更短的等价物
const cityObservables=this.cities.map(this.jobService.getCities)
注意
forkJoin
是脆弱的-如果其中一个城市未知,您在订阅中将一无所获。添加
this.http.get(…).pipe(catchError(err=>of(err))
以处理单个get错误。@RichardMatsen&eric99非常好的建议。我已经为后代更新了。