Prevent Component Reloading in Angular 4 when revisiting the page

My application consists of three main components: 1) Map 2) Search 3) User Profile

Upon logging in, the MAP component is loaded by default. I can navigate to other screens using the header menu link.

I am looking to implement a feature where the map component does not reload when I return to it from another screen or using the back button. Currently, every time I come back to the map screen, all pushpins and related data are reloaded, resetting the user's last view on the map.

Please note that the map is loaded on the ngOnIt event within the map component.

How can I achieve this functionality in Angular 2/4?

A sample screenshot is attached for reference: https://i.sstatic.net/zydzf.jpg

Answer №1

Here is the process I followed to achieve this.

To begin - I integrated the RouteReuseStrategy interface.

import {RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle} from '@angular/router';

export class CustomReuseStrategy implements RouteReuseStrategy {

    handlers: {[key: string]: DetachedRouteHandle} = {};

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        //console.debug('CustomReuseStrategy:shouldDetach', route);
        return !!route.data && !!(route.data as any).shouldDetach;
    }

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        //console.debug('CustomReuseStrategy:store', route, handle);
        this.handlers[route.routeConfig.path] = handle;
    }

    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        //console.debug('CustomReuseStrategy:shouldAttach', route);
        return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
    }

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        //console.debug('CustomReuseStrategy:retrieve', route);
        if (!route.routeConfig) { return null; }
        return this.handlers[route.routeConfig.path];
    }

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        //console.debug('CustomReuseStrategy:shouldReuseRoute', future, curr);
        return future.routeConfig === curr.routeConfig;
    }

}

Next - I included the CustomReuseStrategy provider in the app.module.

import {RouteReuseStrategy} from '@angular/router';
import {CustomReuseStrategy} from './Shared/reuse-strategy';

providers: [
{ provide: RouteReuseStrategy, useClass: CustomReuseStrategy }
]

Lastly - I added the shouldDetach attribute in app.routing.ts

import { Routes, RouterModule } from "@angular/router";
import { MapComponent } from './components/map/map.component';

const ROUTES: Routes = [
{ path: 'maps', component: MapComponent , canActivate:[AuthGuard], data: { shouldDetach: true} },
];

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

What is the definition of a non-arrow React functional component in TypeScript?

Defining types for a React functional component in TypeScript can be done like this: export const Component: React.FC = () => { return // Content }; But how would you define the types for a non-arrow function? function Component() { return // Con ...

Angular design featuring numerical staircase pattern

I'm attempting to implement a numeric version of the staircase pattern using Angular, but I have yet to find the solution. Here is the desired outcome: Below is the code I have developed thus far: main.ts import { Component, Input, OnInit } from &ap ...

I'm trying to troubleshoot this issue - the duration is showing up as NaN years, NaN months, NaN weeks, NaN days, NaN

Currently I am troubleshooting an issue in my ionic project. I have a button and I want to display the date that the user selects. This is my code: age.component.ts import { Component, OnInit } from '@angular/core'; import * as moment from &apo ...

What is the Reason for TypeScript's Inability to Verify the Type of Dynamic Key Object Fields?

How come TypeScript allows the declaration of seta even though it doesn't return objects of type A? type A = { a: '123', b: '456' } // Returns copy of obj with obj[k] = '933' function seta<K extends keyof A> ...

How to implement a reusable module with distinct routes in Angular

In my current angular project, we have various menus labeled A, B, C, D, and E that all utilize the same module. Specifically, menus A, C, and E use the same component/module. My goal is to ensure that when I am on menu A and then click on menu C, the sa ...

Discover the power and ease of combining Angular with OIDC Implicit Flow for seamless

I have integrated the angular-auth-oidc-client package for authentication in my Angular application with our OIDC server. While using the implicit flow, some users face log out issues when the access token expires. To address this, I decided to implement t ...

Using Angular's dependency injection in a project that has been transpiled with Babel

I am currently attempting to transpile my Angular 6 project, which is written in TypeScript, using the new Babel 7. However, I am facing challenges with getting dependency injection to function properly. Every time I try to launch the project in Chrome, I ...

Is there an alternative method to retrieve model value on controller in Angular bootstrap ngbdatepicker since the (change) method has been removed?

Currently, I am working with ngbdatepicker in Bootstrap. I have added a datepicker selector to appcomponent.html and the datepicker is showing up. Now, I need to retrieve that model value into the controller so that I can pass it to the parent appcomponent ...

Create PDF on the server side using Asp.Net Core and then display it in the browser using Angular

In my project, I am utilizing Asp.Net Core and ItextSharp to dynamically create a PDF report which is then sent to the browser. [HttpGet] public async Task<IActionResult> GetStream(string ids) { try { List<int> labRequest ...

Due to a TypeScript error stating that the type '{ Id: number; Name: string; }' cannot be utilized as an index type, I am unable to assign a value for students at this time

I am facing an issue with defining a value for students in TypeScript. It is giving me an error saying that it can't be used as index type. Just to clarify, I have declared id as number (not Number) and Name as string (not String). import { Component ...

Steps to filter types by a singular property assessment

export type HalfSpin = { halfspin: string } export type FullSpin = { fullspin: string } export type SpinType = | HalfSpin | FullSpin export function isHalfSpin(_: SpinType) ...

Incorporate Ng-Survey multiple times within one component

Incorporating the ng-surveys template into my Angular application via has been successful. However, I encountered an issue where when using the template selector *ngFor to display multiple surveys on the same page, the browser treats all the surveys as id ...

Creating a FormGroup dynamically using an observable: A step-by-step guide

My current project involves creating a page with multiple reactive forms, tailored for different countries. These forms are generated based on JSON arrays received from the backend, allowing users to view and update settings individually. As I am uncertain ...

Waiting for the response to come by subscribing in Angular

I am encountering an issue while trying to subscribe to an Observable and assign data from the response. The problem is that my code does not wait for the response before executing the console.log(this.newIds) line, resulting in an empty value being logg ...

Original: Generic for type guard functionRewritten: Universal

I have successfully created a function that filters a list of two types into two separate lists of unique type using hardcoded types: interface TypeA { kind: 'typeA'; } interface TypeB { kind: 'typeB'; } filterMixedList(mixedList$: ...

Angular App Failing to Validate Session Cookie 'sessionId' in AuthGuard

Encountering a perplexing issue with my Angular application where the AuthGuard fails to recognize a session cookie named 'sessionId' correctly. I have successfully implemented user authentication, and the expected behavior is for users to be dir ...

Can you explain the significance of 1x, 3x, etc in the Karma code coverage report for Angular unit testing?

I am a beginner when it comes to Unit Testing in Angular. Recently, I set up karma with code coverage using angular-cli. After running the command ng-test, I checked out the code coverage report and noticed references like 1x, 3x, etc. next to my code line ...

Encountered a 'angular is not defined' error message when attempting to upgrade an AngularJS1 component

I am currently in the process of upgrading AngularJS1 components to Angular6. My approach involves creating wrappers for all existing AngularJS1 components by extending "UpgradeComponent" and placing them under the folder "directive-wrappers" in my example ...

The name 'console' could not be located

I am currently working with Angular2-Meteor and TypeScript within the Meteor framework version 1.3.2.4. When I utilize console.log('test'); on the server side, it functions as expected. However, I encountered a warning in my terminal: Cannot ...

Is it possible to create a sync function that includes a subscription to an observable?

Consider the following code snippet: observableMethod(): Observably { ... Return of([1, 2, 3]); } notObservableMethod(): integer { Let myVal; if (isOM) { this.observableMethod().pipe( first() ).subscribe( val => myVal = val; }); } else { myVal = thi ...