在我的獲取請求中,我需要發送headerParams, 而不是呼叫方法來獲取headerParams如何呼叫和存盤為靜態值?
如何確保其他方法等待標題詳細資訊可用?我正在做最壞的做法。有人幫我嗎?
這是我的服務 ts 檔案:
export class ForecastService extends EntityCollectionServiceBase<OpenWeatherResponse> implements OnInit {
private url = 'https://api.openweathermap.org/data/2.5/forecast';
httpUrlGenerator: any;
headersParams: any; //always underfed
constructor(serviceElementsFactory: EntityCollectionServiceElementsFactory, private http: HttpClient, private notificationService: NotificationsService) {
super('Forecast', serviceElementsFactory);
}
ngOnInit() {
this.headersParams = this.getCurrentLocation().subscribe(header => {
this.headersParams = header; //not working. undefined
});
}
override getAll(): Observable<OpenWeatherResponse[]> {
//need to avoid it
return this.getCurrentLocation().pipe(
map(coords => {
return new HttpParams()
.set('lat', String(coords.latitude))
.set('lon', String(coords.longitude))
.set('units', 'metrics')
.set('appid', '21ef99128f486ce0cb0f0612b7c2d567')
}),
switchMap(params => this.http.get<OpenWeatherResponse[]>(this.url, {params})),
map((value: any) => value.list),
mergeMap((value: OpenWeatherResponse[]) => of([...value])),
filter((value, index) => index % 8 === 0),
map(value => value)
)
}
getForecast() {
//need to avoid it
return this.getCurrentLocation()
.pipe(
map(coords => {
return new HttpParams()
.set('lat', String(coords.latitude))
.set('lon', String(coords.longitude))
.set('units', 'metrics')
.set('appid', '21ef99128f486ce0cb0f0612b7c2d567')
}),
switchMap(params => this.http.get<OpenWeatherResponse>(this.url, {params})),
pluck('list'),
mergeMap(value => of(...value)),
filter((value, index) => index % 8 === 0),
map(value => {
return {
dateString: value.dt_txt,
temp: value.main.temp
}
}),
toArray(),
share()
)
}
getCurrentLocation() {
//looking to call as a first method and need to save in variable
return new Observable<GeolocationCoordinates>(observer => {
window.navigator.geolocation.getCurrentPosition(
position => {
observer.next(position.coords);
observer.complete();
},
err => observer.error(err)
)
}).pipe(
retry(1),
tap({
next: () => this.notificationService.addSuccess('Got your location'),
error: catchError((err) => {
this.notificationService.addError('Failed to get the location');
return throwError(() => new Error(err));
})
}))
}
}
請查看我的評論以了解我的要求。
uj5u.com熱心網友回復:
您可以創建一個共享的 observable 并使用shareReplay添加快取以避免每次呼叫 api
headers$ = this.getCurrentLocation().pipe(
map(coords => {
return new HttpParams()
.set('lat', String(coords.latitude))
.set('lon', String(coords.longitude))
.set('units', 'metrics')
.set('appid', '21ef99128f486ce0cb0f0612b7c2d567')
}),
shareReplay(1) // caching
)
然后以這種方式使用它
getForecast() {
this.headers$.pipe(
switchMap(params => this.http.get<OpenWeatherResponse>(this.url, {params})),
pluck('list'),
...
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390677.html
標籤:有角的 rxjs rxjs-observables rxjs-pipeable-operators
上一篇:避免以角度多次呼叫函式
