我将Angular5与HttpClient一起使用。我创建了一个服务来从JSON API URL获取数据。
这很有效。
但是现在,我想用一个标准来限制结果(spots.lat必须是> minlat和< maxlat)。
我尝试使用map和forEach(见下面?????之间的代码部分),但它不起作用。我怎么能纠正这个?
...
import { HttpClient } from '@angular/common/http';
export interface Spot {
lat: number,
lng: number,
spotname: sring
}
tempspots: <Spot[]>
@Injectable()
export class SpotService {
private spoturl = '<JSON SERVICE URL>';
constructor(
private http: HttpClient,
...
) {}
onGetAllSpots(minlat : number, maxlat : number) : Observable<Spot[]> {
return this.http
.get<Spot[]>(this.spoturl)
// ?????
.map(spots => {
spots.forEach(spot => {
if (spot.lat > minlat && spot.lat < maxlat) {
this.tempspots.push(spot);
}
})
return this.tempspots;
})
// ?????
}
}
答案 0 :(得分:1)
将代码更改为此代码,它应该可以正常工作
.map(spots => {
const tempspots: <Spot[]> = [];
spots.forEach(spot => {
if (spot.lat > minlat && spot.lat < maxlat) {
tempspots.push(spot);
}
})
return tempspots;
})
另一种方法是使用过滤器
.map(spots => {
return spots.filter(spot => {
return spot.lat > minlat && spot.lat < maxlat;
})
})
答案 1 :(得分:0)
较短的版本
.map(spots => spots.filter(spot => spot.lat > minlat && spot.lat < maxlat))