我在服务中使用Angular5和HttpClient。我的服务(感谢Reza)是:
...
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/mergeMapTo';
import 'rxjs/add/observable/timer';
export interface Spot {
lat: number,
lng: number,
spotname: sring
}
tempspots: <Spot[]>
@Injectable()
export class SpotService {
private spoturl = '<JSON SERVICE URL>';
constructor(
private http: HttpClient,
...
) {}
onGetBoundsSpots(minlat, maxlat) : Observable<Spot[]> {
return
Observable.timer(0, 10000).mergeMapTo( // ADDED TO POLL every 10 sec
this.http
.get<Spot[]>(this.spoturl)
) // ADDED TO POLL
.map(spots => {
return spots.filter(spot => {
return spot.lat > minlat && spot.lat < maxlat;
})
})
}
}
这样可以正常运行
但我想每10秒轮询一次这项服务。所以我在上面添加了// ADDED TO POLL
问题:当我在html模板中显示这些信息(_restrictspots)时,_restrictspots在每个轮询中从所有点(无过滤器)更改为仅过滤的点:这需要几秒钟来过滤斑点并显示斑点在此过程中。
当然,我只想显示过滤点......只显示过滤后的点? OnComplete ???像这样的东西。
我的组件:
import { SpotService, Spot } from '../../../shared/spot/spot.service
@Component({
...
template: '<div>Count : {{ _restrictspots.length }}</div>
<div *ngFor="let spot of _restrictspots" ><p>{{ spot.spotname }}</p></div>
<agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom"
(boundsChange)="boundsChange($event)"</agm-map>',
...
})
export class SidebarComponent implements OnInit {
lat: number = 50;
lng: number = 4;
zoom: number = 12;
constructor(private spotserv: SpotService) {}
onRestrictBounds(bounds) {
this.spotserv.onGetBoundsSpots(bounds.getSouthWest().lat(),bounds.getNorthEast().lat()).
subscribe(
resarray => {
this._restrictspots = resarray;
}
)
}
boundsChange(bounds) {
this.onRestrictBounds(bounds);
}
ngOnInit() {
}
}