首页 > 解决方案 > 如何从不同的服务发出异步请求 [Angular]

问题描述

我有 3 项具有类似方法的服务,它们从数据库返回数据。我在我的组件中使用它们,并希望将每个数据响应存储在相应的组件数组中。我如何从其他服务获取其余数据?我对forkjoin等不太熟悉。如果你举个例子会很好。

Services:

export class BrandService {
  private url: string;
  constructor(private http: HttpClient) {
    this.url = 'http://localhost:3000/brands';
  }

  public getJsonBrands(): Observable<any> {
    return this.http.get(this.url);
  }
}
__________________________________________
export class ProductService {
  private url: string;
  constructor(private http: HttpClient) {
    this.url = 'http://localhost:3000/products';
  }

  public getJsonProducts(): Observable<any> {
    return this.http.get(this.url);
  }
}
__________________________________________
export class CategoryService {
  private url: string;
  constructor(private http: HttpClient) {
    this.url = 'http://localhost:3000/categories';
  }

  public getJsonCategories(): Observable<any> {
    return this.http.get(this.url);
  }
}


Component: 

export class ProductsComponent implements OnInit {
  productList: Array<any>;
  brandList: Array<any>;
  categoryList: Array<any>;

  constructor(private productService: ProductService, private brandService: BrandService, private categoryService: CategoryService) {
   this.productService.getJsonProducts().subscribe(
     product => {
       this.productList = product;
     })

  ngOnInit() {

  }
}

_______________________________________
Code below doesnt seem to work, i keep getting console error "this.brandService.getJsonBrands is not a function"

ngOnInit() {
    forkJoin(
      this.productService.getJsonProducts(),
      this.brandService.getJsonBrands(),
      this.categoryService.getJsonCategories()
    )
      .subscribe(([res1, res2, res3]) => {
          this.productList = res1;
          this.brandList = res2;
          this.productList = res3;
          console.log(this.productList, this.brandList, this.productList);
      },
        error1 => {
          console.log(error1);
        });
  }

标签: angularhttprequest

解决方案


使用 Rxjs 中的 ForkJoin 或 CombineLastest,两者之间的区别在这里解释:Rxjs: Observable.combineLatest vs Observable.forkJoin

ngOnInit() {
forkJoin(
      this.productService.getJsonProducts(),
      this.brandService.getJsonBrands(),
      this.categoryService.getJsonCategories() 
    )
    .subscribe(([res1, res2, res3]) => {
      this.productList = res1;
      this.brandList = res2;
      this.categoryList = res3;
    });
}

推荐阅读