I am trying to figure out the OnReuse and CanReuse parts of Angular2's Router and I'm hitting a wall. I modeled my code after the docs here, but for some reason I can't get the methods to call when the route changes. Not sure what I'm doing wrong. Here's my code:
app.component.ts
import {Component, OnInit, NgZone, View} from 'angular2/core';
import {Location, RouteConfig, RouterLink, ROUTER_DIRECTIVES} from 'angular2/router';
import {ProductTable} from './product-table.component';
import {AddProduct} from './add-product.component';
@Component({
selector: 'app'
})
@RouteConfig([
{ path: '/', name: 'ProductTable', component: ProductTable, useAsDefault: true },
{ path: '/add-product', name: 'AddProduct', component: AddProduct }
])
@View({
templateUrl: __resourcePath + '/html/app.html',
directives: [ROUTER_DIRECTIVES, RouterLink]
})
export class AppComponent {
public __resourcePath = __resourcePath;
constructor(public location: Location) {
}
}
product-table.component.ts
import {Component, NgZone} from 'angular2/core';
import {CanReuse, OnReuse, ComponentInstruction} from 'angular2/router';
import {NgClass} from 'angular2/common';
@Component({
selector: 'product-table',
templateUrl: __resourcePath + '/html/product-list.html',
directives: [NgClass]
})
export class ProductTable implements CanReuse, OnReuse {
public storeProducts: Store_Product__c[] = [];
public selectedStore: string;
public selectedCategory: string;
public errors: { [id: string]: string } = {};
constructor(private zone: NgZone) {
}
routerCanReuse(next: ComponentInstruction, prev: ComponentInstruction) {
console.log('routerCanReuse fired');
return true;
}
routerOnReuse(next: ComponentInstruction, prev: ComponentInstruction) {
console.log('Reusing!');
console.log(next);
this.selectedStore = next.params['selectedStore'];
this.selectedCategory = next.params['selectedCategory'];
this.storeProducts = next.params['storeProducts'];
}
}
I think the docs are not clear enough, or we just looked up a wrong doc.
Angular will not consider a component is resusable if router navigates to a component of different type. The following explanation is extracted from Angular's source
It is likely that you never navigate from
ProductTable
toProductTable
. SoCanReuse
hook is never called. But you can try reusing strategy in components likeProductDetail
where you will navigate from one item's detail to the next item's detail.