Angular 2+:基于API响应的路由

13

假设我有以下内容:

const routes = [
  { 
    path: 'product/:id',
    component: ProductDetailsComponent,
  }
  { 
    path: 'search',
    component: SearchResultsComponent,
  }
]

现在说

product/1 - 是一部由DigitalMediaComponent渲染的电影

product/2 - 是一台由ProductDetailsComponent展示的电视

product/3 - 是一个洗衣机/烘干机捆绑销售,以BundleComponent的形式呈现

product/4 - 是一个床垫系列,包括床垫、框架、罩子、床单、枕头等,购买前可以选择许多东西,如颜色、尺码、纱线数量等

product/5 - 是汽车产品,比如轮胎,因此需要使用TireComponent- 这需要一个适配器组件,通过年份/品牌/型号/修剪选择和许多其他自定义项,才能购买

还有很多类似的产品。

显然,有些组件在这些产品之间是可重用的,但总体上它们大不相同。因此,我想延迟加载(或延迟下载)包含这些组件的JavaScript文件(和CSS文件),当展示轮胎时,我不需要MoviePreviewComponent

我读过很多例子,它们都讲解了一个非常简单的情况,即路由和组件之间的一对一关系,比如

{ path: 'product/:id', loadChildren: 'product/ProductDetailsComponent' }
or
{ path: 'product/:id', loadChildren: () => System.import('./product/ProductDetailsComponent').then(mod => mod.default) }

有没有一种方法可以在导航到路由时调用API, 并根据API的响应使用System.import('...')来延迟下载模块?

我不想导航到一个中间组件并从那里加载,因为当用户从搜索结果(或站点中任何其他促销横幅,可能构建于Angular 2或非Angular 2)中点击产品时, 如果页面需要一点时间才能加载,他们可能会按esc键然后单击其他东西。这是正常的浏览器行为,我不想失去它。

即使我最终得到了中间组件,我该如何加载动态模块呢?

ngOnInit() {
  let id = this.route.snapshot.params['id'];
  fetch('/my/api/' + id)
    .then(response => response.json())
    .then(data => {
      System.import('./page/' + data.componentType)
        .then(
          // then what do I do to register this module with Angular
          // and replace this in the <router-outlet>
    })

}

你可以在路由模块中配置它们。你什么时候检索数据? - Aravind
不明白你所说的路由模块是什么意思。当用户从搜索结果中点击某个产品后,数据必须从API中检索。 - rrag
这是一个单页应用程序吗?如果是的话,请使用*ngIf isLoading布尔型可观察指示器来限制广告内容... 将其放置在您的主应用程序页面中。至于模块化部分... 我仍然在努力理解这一部分。 - JGFMK
2个回答

0

0

我认为对于良好的设计,应该尝试这样做:

      ngOnInit(): void {
              this.ServiceOfArray.getArray(id)
            .then(u => this.showData(u));
    }
    enter code here

showData(data: Data) {
        this.data= data;
    }


Service.class
apiEndpoint: "http://localhost:52246/api";

       getArray(Id: number): Promise<SomeData> {
            var url = this.config.apiEndpoint + "/somedata/" + Id;
            return this.http.get(url)
                .map(response => response.json() as SomeData)
                .toPromise();
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接