首页 > 解决方案 > 从多个组件调用方法

问题描述

我有一个从 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() 方法

标签: arraysangularhttprequest

解决方案


您正在返回 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 参数,这可能对您有所帮助。


推荐阅读