【问题标题】:Angular 2+: Routing based on response from apiAngular 2+:基于 api 响应的路由
【发布时间】:2017-08-10 11:24:41
【问题描述】:

假设我有以下

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) }

有什么办法可以

  1. 在导航到路线时调用 api
  2. 并根据对该 api 的响应使用 System.import('...') 延迟下载模块

我不想导航到插页式组件并从那里加载,因为当用户从搜索结果(或整个网站的任何其他促销横幅中点击产品时,可能会或可能不会使用 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>
    })

}

【问题讨论】:

  • 您可以在路由模块本身中配置它们。您什么时候检索数据?
  • 不遵循路由模块的意思。用户点击搜索结果中的产品后,必须从 api 中检索数据
  • 这是单页应用程序吗?如果是这样,广告内容是否由 *ngIf isLoading boolean Observable 指示器调节...将其放在您的主应用程序页面中。至于模块化部分...我仍然对那部分感兴趣。

标签: angular


【解决方案1】:

看看这是否有帮助: 您可以在此链接 [https://angular.io/guide/dynamic-component-loader].您只需要创建您的 id 和组件的映射。查看文章中给出的这个 plunkr [https://embed.plnkr.co/?show=preview].

【讨论】:

    【解决方案2】:

    我认为对于好的设计,请尝试这样:

          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();
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      相关资源
      最近更新 更多