When the route changes, routerCanReuse and routerOnReuse are not invoked

I am currently exploring the functionalities of Angular2's Router, specifically focusing on OnReuse and CanReuse. I have followed the documentation provided here, but I seem to be encountering difficulties in getting the methods to trigger when the route changes. I am unsure where I might have made a mistake. Below is the code snippet that I have implemented:

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'];
    }
}

Answer №1

It seems as though the documentation may not be entirely clear, or perhaps we have inadvertently referred to the wrong document.

In Angular, a component is not considered reusable if the router navigates to a component of a different type. The explanation below is taken directly from the source code of Angular's router outlet:

The router-outlet's reuse method is called by the Router during the recognition phase of a navigation. If the new child component has a different Type than the existing child component, this will result in false. You cannot reuse an old component when the new component is of a different Type. Otherwise, this method will defer to the child component's routerCanReuse hook if it exists, or resolve to true if the hook is not present.

It is possible that you have never navigated from ProductTable to ProductTable, hence the CanReuse hook is never invoked. However, you can attempt to implement a reusing strategy in components like ProductDetail where you navigate from one item's detail to the next item's detail.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

the behavior subject remains static and does not update

Working on setting my language in the BehaviorSubject with a default value using a LanguageService. The service structure is as follows import {Injectable} from '@angular/core'; import * as globals from '../../../environments/globals'; ...

Redirecting an angular application to a designated URI using nginx

I'm currently working on an Angular app that needs to be hosted on a URI like www.xyz.com/abc. I have set up an EC2 instance with nginx server running for this purpose. The website seems to be functioning well and is successfully hosted, but the probl ...

Experiencing the error "f.ngOnChanges is not a function in target es5" while using Angular4

Encountering an issue f.ngOnChanges is throwing an error The problem arises when my tsconfig.json file is configured to target es5. However, everything works fine if I set the target to es6. Is there a way to make ngOnChange function properly with es ...

JHipster form validation is failing to function properly

I have a specific class structure that is defined as follows in JDL entity Address { address String required, city String required, postalCode String required, country String required, } entity MainEntity { <some fields> } relationship O ...

The Angular Material date picker unpredictably updates when a date is manually changed and the tab key is pressed

My component involves the use of the Angular material date picker. However, I have encountered a strange issue with it. When I select a date using the calendar control, everything works fine. But if I manually change the date and then press the tab button, ...

Displaying a segment of information extracted from a JSON array

I'm currently tackling a project that involves using React, Redux, and TypeScript. Within the JSON file, there is a key-value pair: "data_start": "2022-09-02" Is there a way to display this date in a different format, specifical ...

Having trouble with GraphQL Explorer and Express Sessions compatibility?

Struggling to implement a login system using GraphQL and Express, but facing issues with session persistence. Despite logging in, req.session.userId remains undefined. Code snippet: (async () => { await connect(process.env.MONGO_URI!, { dbName: "ex ...

Developing an Azure pipeline to generate artifacts for an Angular Universal application

I am currently facing an issue with deploying my Angular Universal app to Azure Web App Service. Running npm run build:ssr && npm run serve:ssr locally works perfectly fine. Similarly, running npm run start without ssr rendering also works smoothly ...

Is Typescript familiar with the import -> require syntax, but unfamiliar with the require -> import syntax?

My code includes a simple file that utilizes the ES6 module loader: 1.ts import {foo} from "./2" foo('hello'); 2.ts function foo (a){console.log(a);}; export {foo} When the tsconfig is configured as follows: "module": "commonjs", We can o ...

Enhance the display in Angular2

Just started working with Angular 2 and I've encountered a problem. I have an API that loads a JavaScript file in my project. The issue is, I need to use this JS file and cannot modify it. Essentially, this JS file has some methods that make AJAX call ...

Expanding on Angular's virtual scroll feature: automatically add new items as you reach the bottom of the

I'm facing a challenge in my Angular application where I want to implement virtual scroll. The items displayed on the list are the outcome of a remote paged search. My goal is to fetch more results (trigger the next page) every time I scroll down to t ...

Effortless method for combining PHP API with Angular 2 application on your computer

Currently, I am developing a new Angular 2 application that interacts with a REST API built on PHP. To simulate the data flow, I have generated mock data in a json file for the front end. The PHP REST API was created using MAMP and has been tested succes ...

Sending an interface object to a custom component using ngFor

I'm facing a challenge with this task. The child component I'm working on includes the following: ChildComponent @Input() record : InterfaceRecord; Where InterfaceRecord is defined as: export interface InterfaceRecord { ti ...

How can we dynamically update property values in a ngFor loop by utilizing the click method?

Here is a TypeScript file I am working with: <md-card style="display: inline-block;" *ngFor="let people of peoples"> <p> {{people.name}} </p> <p *ngIf="people.showAge"> {{people.age}} </p> < ...

The Cypress tests run successfully on a local machine, but encounter issues when running on Gitlab CI

My current setup involves utilizing Cypress to test my Angular application. Interestingly, everything runs smoothly when I execute the tests locally. However, the scenario changes once I run the tests in Gitlab CI as it ends up failing. Looking at my pack ...

Angular application encountering a 401 unauthorized error when attempting to connect to TFS API

Having trouble with an API get request in my initial Angular project. I'm attempting to retrieve all projects from a server using the correct URL (which works in Postman and my browser), as well as a token generated from my TFS account. Despite this, ...

Using TypeScript and webpack, include the access_token in the http header when making requests with axios

I need to include an access_token in the header of axios, following this example: https://github.com/axios/axios#global-axios-defaults Currently, I am fetching the access_token using razor syntax, which is only accessible in CSHTML files. https://github ...

Three.js and Angular - the requested function cannot be found

In my latest project, I created a basic application using Angular 4 and three.js to display a cube. The main part of the code resides in an Angular component called ViewerComponent, where the cube is rendered. I've simplified the relevant part of the ...

Is using global variables as a namespace a good practice? Creating ambient TypeScript definitions in StarUML

I'm currently working on creating TypeScript type definitions for the StarUML tool. While I've been successful in defining most of the API, I've hit a roadblock when it comes to linking a JavaScript global variable ("type" in this case) with ...

Creating a generic hashmap that can accept dynamic keys and an array of type T

In my attempt to create a robust typing interface for a hashmap in typescript, The hashmap consists of a key with a dynamic string name, and a values array containing a Generic type. I attempted to define the interface as follows: export interfa ...