【发布时间】: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);
});
}
【问题讨论】:
-
这只是懒惰,如果你搜索“parallel http requests angular”,你会发现很多资源解释了如何做到这一点
标签: angular httprequest