У меня есть метод, который заставляет http получить запрос от URL, этот метод вызывается из нескольких компонентов, каждый вызов выполняет запрос 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 после первого вызова, не должен ли массив заполняться и возвращаться?
Обратите внимание, что компоненты вызывают метод getProducts () в ngOnInit ()