angular - 如何从不同的服务发出异步请求 [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);
});
}
解决方案
使用 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;
});
}
推荐阅读
- java - 通过 Selenium Java TestNG 执行测试时出现“无法实例化类”错误
- arrays - 切割排序切片的最佳方法
- json - 使用 PySpark 从 Cloudera CDSW 项目中读取文件
- android - 将图像从列表视图传递到另一个活动
- javascript - 如何使用 SAP Leonardo 的 API 翻译?
- c++ - 您应该在模板代码中完全避免使用 const 吗?
- kubernetes - 如何将文件从一个命名空间中的 pod 复制到另一个命名空间中的 pod
- javascript - 需要对一些基本设置进行一些说明
- c - 获取进程返回 -1073741819 (0xC0000005) 错误而不是回答
- ios - 我无法在我的 iOS 设备上运行我的应用程序,即使它们已更新