Say I have the following
const routes = [
{
path: 'product/:id',
component: ProductDetailsComponent,
}
{
path: 'search',
component: SearchResultsComponent,
}
]
now say
product/1 - is a movie which is rendered by DigitalMediaComponent
product/2 - is say a TV by ProductDetailsComponent
product/3 - is a washer/dryer bundle, rendered as a BundleComponent
product/4 - is a mattress collection, this includes, a mattress, frames, covers, sheets, pillows, and once can choose a number of things, color, sizes, thread count and such before buying
product/5 - is an automotive product say a tire, so this renders a TireComponent - This needs a fitmentmodule, with year/make/model/trim selection, and many other customizations before one can buy
and the list goes on.
Now obviously, there are some components which are reused between some of these, but overall they are largely different from each other. So I want to lazy load (or lazy download) the javascript files (and css) which contain these components, I dont need the MoviePreviewComponent when showing tires.
I have read many examples and they all talk about a very simple case of one to one relation between route and component, like
{ path: 'product/:id', loadChildren: 'product/ProductDetailsComponent' }
or
{ path: 'product/:id', loadChildren: () => System.import('./product/ProductDetailsComponent').then(mod => mod.default) }
Is there a way where I can
System.import('...') to lazy download the moduleI don't want to navigate to an interstitial component and load from there because when the user clicks on a product from search results (or from any other promotional banners throughout the site, which might or might not be built with angular 2), and if it takes a bit for the page to load, they could press esc and click something else. This is normal browser behavior and I don't want to lose that
Even if I do end up with an interstitial component, how would I go about loading the dynamic module in?
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>
})
}
See if this helps: You can create a dynamic component loader following this link[https://angular.io/guide/dynamic-component-loader]. You will just have to create a mapping of you ids and components. Check out this plunkr given in the article[https://embed.plnkr.co/?show=preview].
I think for good design try to make like this :
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();
}