arrays - 从多个组件调用方法
问题描述
我有一个从 url 发出 http get 请求的方法,这个方法被多个组件调用,每个调用都发出 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() 方法
解决方案
您正在返回 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 参数,这可能对您有所帮助。
推荐阅读
- c++ - 如果找到“\r”,则 C++ While 循环不退出
- firebase - React Native Firebase - setUserProperties() - 设置多个属性
- python - 两个日期之间的所有星期天,使用 pandas 的索引
- python - 绘制插值图时低于零值问题
- xcode - xcode 其他链接器标志:-force_load 不起作用
- angular - Angular 和 Element 隐式具有“任何”类型,因为类型“IData”没有索引签名
- java - Oracle - 如何在循环中使用 START WITH(休眠选择)
- inheritance - IdentityServer4 Skoruba 新字段参数丢失
- php - 在应用程序上实现 JWT(理解 JWT 的概念)
- java - 如何将标题存储在所有拆分的 CSV 文件中?