我有一个方法,它使url发出http获取请求,该方法从多个组件中调用,每个调用都发出http请求,因此我将结果存储在数组中,以便在第二次调用时返回该数组,并且不会再次发出http请求,但不会返回该数组,而是再次发出http请求。
这是我的代码:
export class ProductsService {
public currency: string = '';
public products: Product[];
// Initialize
constructor(private http: HttpClient, private toastrService: ToastrService) {
}
// Get Products
public getProducts(): Observable<Product[]> {
return this.getAllProducts();
}
private getAllProducts(): Observable<Product[]> {
if (this.products) {
return of(this.products);
} else {
return this.getIp().pipe(
switchMap(country => {
this.currency = this.getCurrency(country);
return this.http.get('http://localhost:8080/products/getAllProducts?currency=' + this.currency).pipe(
map((res: any) => {
this.products = res;
return this.products;
})
);
})
);
}
}
private getIp() {
return this.http.get<any>(('http://ip-api.com/json/?fields=countryCode')).pipe(
map(r => r.countryCode)
);
}
private getCurrency(country: string): string {
let currency;
if (country === 'JO') {
currency = 'JOD';
} else if (country === 'AE') {
currency = 'AED';
} else if (country === 'SA') {
currency = 'SAR';
} else if (country === 'GB') {
currency = 'GBP';
} else if (country === 'DE') {
currency = 'EUR';
} else if (country === 'KW') {
currency = 'KWD';
} else if (country === 'EG') {
currency = 'EGP';
} else {
currency = 'USD';
}
return currency;
}
}
在这里我做错了什么,为什么该方法在第一次调用后再次发出http请求,难道不应该填充并返回数组吗?
请注意,组件正在ngOnInit()中调用方法getProducts()
答案 0 :(得分:0)
您将返回可观察到的get。每次调用这些方法时,它们都会开始对端点进行新的预订。
public getProducts(): Observable<Product[]> {
return this.getAllProducts();
}
private getAllProducts(): Observable<Product[]> {
if (this.products) {
return of(this.products);
} else {
return this.getIp().pipe(
switchMap(country => {
this.currency = this.getCurrency(country);
return this.http.get('http:/ <== this is an observable
您需要一项服务来同步这些内容。
我有一个示例用于简单状态的服务,我曾用来同步StackBlitz上许多组件的URL参数,这可能会对您有所帮助。