【发布时间】:2018-12-24 17:02:52
【问题描述】:
我有问题,我有ProductsService,它从服务器调用数据并存储在Array 中,我有ProductsComponent 组件,它是父组件,我有ProductsListComponent 和SingleProductComponent,这是子组件.流程是,在ProductsService我有方法:
getCategoryFromServer() {
this.dataStorageServiceServiceta.getCategory().subscribe((category: CategoryModel[]) => {
this.categoryModule = category;
this.cateogoryChange.next(this.categoryModule.slice())
})
}
我有 categoryModule 存储数据的数组。
在ProductsComponent中的ngOnInit方法中我调用getCategoryFromServer方法:
ngOnInit() {
this.productsService.getCategoryFromServer();
}
ProductsComponent 的模板是:
<div class="row">
<div class="col-md-3 col-sm-12">
<app-products-list></app-products-list>
</div>
<div class="col-md-9 col-sm-12">
<div class="row" >
<router-outlet></router-outlet>
</div>
</div>
</div>
我的屏幕显示app-products-list 组件,我从serevice 调用数据,您可以在图像上看到它的样子。 enter image description here。当我单击此列表中的某些项目时,使用[routerLink]="[products.name]" 会显示我的组件ProductListItemsComponent,看起来像这样enter image description here。
问题是当我刷新页面并首先执行SingleProductComponent 之后执行ProductsComponent 并且我的数组为空。你知道我该如何解决这个问题吗?
我的路由模块是:
const productsRoutes: Routes = [
{
path: 'productsList', component: ProductsComponent, children: [
{ path: ':category', component: ProductListItemsComponent },
{ path: ':category/:id', component: SingleProductComponent }
]
},
]
你可以从github下载https://github.com/milos2611/angular-shop.gitgithub
【问题讨论】:
-
你是否从两个组件访问
categoryModule数组? -
是的,我对这两个组件都使用了
categoryModule。可以在github项目中看到。 -
@KinJong 使用
ngif条件,如果获取 API 请求数据则加载子组件。 -
任何示例如何实现?
标签: angular typescript