【问题标题】:How to make async requests from different services [Angular]如何从不同的服务发出异步请求 [Angular]
【发布时间】:2019-03-23 16:08:09
【问题描述】:

我有 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);
        });
  }

【问题讨论】:

  • 来自 Rxjs link 的 ForkJoin 和一个角度示例 link
  • 这只是懒惰,如果你搜索“parallel http requests angular”,你会发现很多资源解释了如何做到这一点

标签: angular httprequest


【解决方案1】:

您可以使用combineLatestforkJoin。用法非常相似。 但是你应该取消订阅combineLatest,这与forkJoin不同。

import { Subscription, combineLatest } from 'rxjs';

sub: Subscription;
myData: any;

ngOnInit() {
  this.sub = combineLatest(
    this.brandService.getJsonBrands,
    this.productService.getJsonProducts,
    this.categoryService.getJsonCategories
  ).subscribe(([brands, products, categories]) => {
    this.myData = {brands, products, categories};
    console.log('this.myData', this.myData);
  });
}

ngOnDestroy() {
    this.sub.unsubscribe();
}

forkJoin - 当所有 observables 完成后,发出每个 observables 最后发出的值。

combineLatest - 当任何 observable 发出一个值时,发出每个 observable 的最新值。

【讨论】:

  • 我是否在“myData”(sub:any) 之后声明“sub”变量?
  • “类型 'ProductsComponent' 上不存在属性 'sub'”并且 [brands, products, categories] 得到“类型 'Observable' 不是数组类型”。它在控制台中记录:“您在预期流的位置提供了‘未定义’。您可以提供 Observable、Promise、Array 或 Iterable。”
  • @BobbyFade 我已添加 - 订阅:订阅。更新答案
  • [brands, products, categories] 这不断得到“Type 'Observable' is not an array type”
  • @BobbyFade 更改方法中的输出类型 - Observable 为 Observable。或者删除它。
【解决方案2】:

您必须订阅产品服务等其他服务并将其包含在提供程序中

    constructor(private productService: ProductService,
                private brandService: BrandService,
                private categoryService: CategoryService) {
        this.productService.getJsonProducts().subscribe(product => {
          this.productList = product;
        })
        this.brandService.getJsonBrands().subscribe(brands=> {
           this.brandList = brands;
        })
        this.CategoryService.getJsonCategories().subscribe(categories=> {
           this.categoryList= categories;
        })
    }

【讨论】:

  • 我不断收到“this.brandService.getJsonBrands 不是函数”错误
【解决方案3】:

使用 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;
    });
}

【讨论】:

    猜你喜欢
    • 2014-03-07
    • 1970-01-01
    • 2021-07-26
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多