gpt4 book ai didi

Angular RxJS mergeMap 类型

转载 作者:太空狗 更新时间:2023-10-29 18:12:27 24 4
gpt4 key购买 nike

尝试使用 http.get 请求 URL 将经度和纬度从地理位置服务提取到 list.service

第一期:

businesses Property 'businesses' does not exist on type '{}'

感谢在此问题和时间上的帮助

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 属性,这就是它提示的原因。您可以使用:

  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

关于Angular RxJS mergeMap 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52010000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com