Angular RxJS mergeMap类型 [英] Angular RxJS mergeMap types
问题描述
尝试使用http.get
请求URL将地理位置服务中的经度和纬度拉入list.service
.
Trying to pull the longitude and latitude from a geo location service into list.service
using http.get
request URL.
第一期:
businesses属性"businesses"在类型"{}"上不存在
businesses Property 'businesses' does not exist on type '{}'
感谢有关此问题和时间的帮助
Appreciate the help on this issue and the time
list.service.ts
:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { List } from '../models/list.model';
import { map } from 'rxjs/operators';
import { GeolocationService } from '../services/geolocation.service';
import { mergeMap } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ListService {
private serverApi = 'http://localhost:3000';
constructor(private http: HttpClient, private geoServ: GeolocationService) { }
public getAllLists(): Observable<List[]> {
return this.geoServ.getGeoLocation().pipe(
mergeMap<{businesses: List[]}>(({ latitude, longitude }) =>
this.http.get(`${this.serverApi}/yelp/${longitude}/${latitude}`).pipe(
)
),
map(res => res.businesses));
}
}
geolocation.service.ts
:
import { Injectable } from '@angular/core';
import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent, SubscriptionLike, PartialObserver } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class GeolocationService {
constructor() { }
getGeoLocation() {
return new Observable((observer) => {
console.log('Geolocation working!');
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
const success = (pos) => {
const crd = pos.coords;
console.log(`Longitude : ${crd.longitude}`);
const location = {
"latitude" : crd.longitude,
"longitude": crd.longitude
};
observer.next(location);
observer.complete();
};
const error = (err) => {
console.warn(`ERROR(${err.code}): ${err.message}`);
observer.error(err);
observer.complete();
};
navigator.geolocation.getCurrentPosition(success, error, options);
});
}
}
list.model.ts
:
export interface List {
id: string;
name?: string;
rating?: number;
review_count?: number;
url?: string;
location: string;
display_name?: string;
image_url?: string;
is_closed?: boolean;
}
添加了model.ts
以帮助澄清
推荐答案
您的代码说您的GET返回了List[]
,但是数组没有businesses
属性,这就是它抱怨的原因.您可以使用:
Your code says that your GET returns a List[]
, but an array wont have a businesses
property, which is why it's complaining. You can use:
public getAllLists(): Observable<List[]> {
return this.geoServ.getGeoLocation().pipe(
mergeMap(({ latitude, longitude }) =>
this.http.get<any>(`${this.serverApi}/yelp/${longitude}/${latitude}`)
),
map(res => res.businesses));
}
这将编译,但是如果响应确实是一个数组,则Observable
可能最终发出undefined
This will compile, but if the response really is an array, the Observable
may end up emitting undefined
这篇关于Angular RxJS mergeMap类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!