【问题标题】:Routing execute children component before parent using params路由使用参数在父组件之前执行子组件
【发布时间】:2018-12-24 17:02:52
【问题描述】:

我有问题,我有ProductsService,它从服务器调用数据并存储在Array 中,我有ProductsComponent 组件,它是父组件,我有ProductsListComponentSingleProductComponent,这是子组件.流程是,在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


【解决方案1】:

您可以从两个组件创建一个 get 方法来访问数组。就像在产品组件中一样,

get categoryModule(): Your_type[] {
   this.ProductsService.categoryModule;
}

在两个组件中都这样做,它总是会从产品服务中获得价值。

<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>
  {{categoryModule | json }}
</div>

【讨论】:

  • 是的,我有方法。 this.subscription = this.route.params .subscribe( (params: Params) =&gt; { this.categoryName = params['category']; this.singleProducts = this.productsService.getListOfProduct(this.categoryName); }) 但这在我从服务器调用数据的父组件之前执行,这就是问题。我想先执行父组件ProductsComponent,然后再执行ProductListItemsComponent
  • 是否需要先执行哪个组件?因为get方法会随着服务数据的更新而更新。
  • 是的,完全正确。那是我的问题。
猜你喜欢
  • 2017-04-24
  • 1970-01-01
  • 2019-07-06
  • 2019-10-22
  • 2016-09-04
  • 1970-01-01
  • 2021-05-31
  • 2017-12-14
  • 2016-12-19
相关资源
最近更新 更多